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
53d17faab3ab784be1ff55470acde9a9326c58c3
awa/src/awa-modules.ads
awa/src/awa-modules.ads
----------------------------------------------------------------------- -- awa-modules -- Application Module -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Log.Loggers; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Serialize.IO; with Util.Listeners; with EL.Expressions; with ASF.Beans; with ASF.Applications; with ADO.Sessions; with AWA.Events; limited with AWA.Applications; -- == Introduction == -- A module is a software component that can be integrated in the -- web application. The module can bring a set of service APIs, -- some Ada beans and some presentation files. The AWA framework -- allows to configure various parts of a module when it is integrated -- in an application. Some modules are designed to be re-used by -- several applications (for example a _mail_ module, a _users_ -- module, ...). Other modules could be specific to an application. -- An application will be made of several modules, some will be -- generic some others specific to the application. -- -- == Registration == -- The module should have only one instance per application and it must -- be registered when the application is initialized. The module -- instance should be added to the application record as follows: -- -- type Application is new AWA.Applications.Application with record -- Xxx : aliased Xxx_Module; -- end record; -- -- The application record must override the `Initialize_Module` procedure -- and it must register the module instance. This is done as follows: -- -- overriding -- procedure Initialize_Modules (App : in out Application) is -- begin -- Register (App => App.Self.all'Access, -- Name => Xxx.Module.NAME, -- URI => "xxx", -- Module => App.User_Module'Access); -- end Initialize_Modules; -- -- The module is registered under a unique name. That name is used -- to load the module configuration. -- -- == Configuration == -- The module is configured by using an XML or a properties file. -- The configuration file is used to define: -- -- * the Ada beans that the module defines and uses, -- * the events that the module wants to receive and the action -- that must be performed when the event is posted, -- * the permissions that the module needs and how to check them, -- * the navigation rules which are used for the module web interface, -- * the servlet and filter mappings used by the module -- -- The module configuration is located in the *config* directory -- and must be the name of the module followed by the file extension -- (example: `module-name`.xml or `module-name`.properties). -- -- package AWA.Modules is type Application_Access is access all AWA.Applications.Application'Class; -- ------------------------------ -- Module manager -- ------------------------------ -- -- The <b>Module_Manager</b> represents the root of the logic manager type Module_Manager is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with private; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Module -- ------------------------------ type Module is abstract new Ada.Finalization.Limited_Controlled with private; type Module_Access is access all Module'Class; -- Get the module name function Get_Name (Plugin : Module) return String; -- Get the base URI for this module function Get_URI (Plugin : Module) return String; -- Get the application in which this module is registered. function Get_Application (Plugin : in Module) return Application_Access; -- Find the module with the given name function Find_Module (Plugin : Module; Name : String) return Module_Access; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : String := "") return String; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : Integer := -1) return Integer; -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String; -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class); procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config); -- Initialize the configuration file parser represented by <b>Parser</b> to recognize -- the specific configuration recognized by the module. procedure Initialize_Parser (Plugin : in out Module; Parser : in out Util.Serialize.IO.Parser'Class) is null; -- Configures the module after its initialization and after having read its XML configuration. procedure Configure (Plugin : in out Module; Props : in ASF.Applications.Config) is null; -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class); -- Get the database connection for reading function Get_Session (Manager : Module) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session; -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access); -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access); -- Find the module with the given name in the application and add the listener to the -- module listener list. procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access); -- Remove a listener from the module listener list. procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access); -- Finalize the module. overriding procedure Finalize (Plugin : in out Module); type Pool_Module is abstract new Module with private; type Session_Module is abstract new Module with private; generic type Manager_Type is new Module_Manager with private; type Manager_Type_Access is access all Manager_Type'Class; Name : String; function Get_Manager return Manager_Type_Access; -- Get the database connection for reading function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session; -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class); -- ------------------------------ -- Module Registry -- ------------------------------ -- The module registry maintains the list of available modules with -- operations to retrieve them either from a name or from the base URI. type Module_Registry is limited private; type Module_Registry_Access is access all Module_Registry; -- Initialize the registry procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config); -- Register the module in the registry. procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String); -- Find the module with the given name function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access; -- Find the module mapped to a given URI function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access; -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)); private use Ada.Strings.Unbounded; type Module is abstract new Ada.Finalization.Limited_Controlled with record Registry : Module_Registry_Access; App : Application_Access := null; Name : Unbounded_String; URI : Unbounded_String; Config : ASF.Applications.Config; Self : Module_Access := null; Listeners : Util.Listeners.List; end record; -- Map to find a module from its name or its URI package Module_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Module_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Module_Registry is limited record Config : ASF.Applications.Config; Name_Map : Module_Maps.Map; URI_Map : Module_Maps.Map; end record; type Module_Manager is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with record Module : Module_Access := null; end record; type Pool_Module is new Module with record D : Natural; end record; type Session_Module is new Module with record P : Natural; end record; use Util.Log; -- The logger (used by the generic Get function). Log : constant Loggers.Logger := Loggers.Create ("AWA.Modules"); end AWA.Modules;
----------------------------------------------------------------------- -- awa-modules -- Application Module -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Log.Loggers; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Serialize.IO; with Util.Listeners; with EL.Expressions; with ASF.Beans; with ASF.Applications; with ADO.Sessions; with AWA.Events; limited with AWA.Applications; -- == Introduction == -- A module is a software component that can be integrated in the -- web application. The module can bring a set of service APIs, -- some Ada beans and some presentation files. The AWA framework -- allows to configure various parts of a module when it is integrated -- in an application. Some modules are designed to be re-used by -- several applications (for example a _mail_ module, a _users_ -- module, ...). Other modules could be specific to an application. -- An application will be made of several modules, some will be -- generic some others specific to the application. -- -- == Registration == -- The module should have only one instance per application and it must -- be registered when the application is initialized. The module -- instance should be added to the application record as follows: -- -- type Application is new AWA.Applications.Application with record -- Xxx : aliased Xxx_Module; -- end record; -- -- The application record must override the `Initialize_Module` procedure -- and it must register the module instance. This is done as follows: -- -- overriding -- procedure Initialize_Modules (App : in out Application) is -- begin -- Register (App => App.Self.all'Access, -- Name => Xxx.Module.NAME, -- URI => "xxx", -- Module => App.User_Module'Access); -- end Initialize_Modules; -- -- The module is registered under a unique name. That name is used -- to load the module configuration. -- -- == Configuration == -- The module is configured by using an XML or a properties file. -- The configuration file is used to define: -- -- * the Ada beans that the module defines and uses, -- * the events that the module wants to receive and the action -- that must be performed when the event is posted, -- * the permissions that the module needs and how to check them, -- * the navigation rules which are used for the module web interface, -- * the servlet and filter mappings used by the module -- -- The module configuration is located in the *config* directory -- and must be the name of the module followed by the file extension -- (example: `module-name`.xml or `module-name`.properties). -- -- package AWA.Modules is type Application_Access is access all AWA.Applications.Application'Class; -- ------------------------------ -- Module manager -- ------------------------------ -- -- The <b>Module_Manager</b> represents the root of the logic manager type Module_Manager is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with private; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module_Manager; Name : String; Default : String := "") return String; -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. function Get_Config (Plugin : in Module_Manager; Config : in ASF.Applications.Config_Param) return String; -- ------------------------------ -- Module -- ------------------------------ type Module is abstract new Ada.Finalization.Limited_Controlled with private; type Module_Access is access all Module'Class; -- Get the module name function Get_Name (Plugin : Module) return String; -- Get the base URI for this module function Get_URI (Plugin : Module) return String; -- Get the application in which this module is registered. function Get_Application (Plugin : in Module) return Application_Access; -- Find the module with the given name function Find_Module (Plugin : Module; Name : String) return Module_Access; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : String := "") return String; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : Integer := -1) return Integer; -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String; -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class); procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config); -- Initialize the configuration file parser represented by <b>Parser</b> to recognize -- the specific configuration recognized by the module. procedure Initialize_Parser (Plugin : in out Module; Parser : in out Util.Serialize.IO.Parser'Class) is null; -- Configures the module after its initialization and after having read its XML configuration. procedure Configure (Plugin : in out Module; Props : in ASF.Applications.Config) is null; -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class); -- Get the database connection for reading function Get_Session (Manager : Module) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session; -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access); -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access); -- Find the module with the given name in the application and add the listener to the -- module listener list. procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access); -- Remove a listener from the module listener list. procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access); -- Finalize the module. overriding procedure Finalize (Plugin : in out Module); type Pool_Module is abstract new Module with private; type Session_Module is abstract new Module with private; generic type Manager_Type is new Module_Manager with private; type Manager_Type_Access is access all Manager_Type'Class; Name : String; function Get_Manager return Manager_Type_Access; -- Get the database connection for reading function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session; -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class); -- ------------------------------ -- Module Registry -- ------------------------------ -- The module registry maintains the list of available modules with -- operations to retrieve them either from a name or from the base URI. type Module_Registry is limited private; type Module_Registry_Access is access all Module_Registry; -- Initialize the registry procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config); -- Register the module in the registry. procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String); -- Find the module with the given name function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access; -- Find the module mapped to a given URI function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access; -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)); private use Ada.Strings.Unbounded; type Module is abstract new Ada.Finalization.Limited_Controlled with record Registry : Module_Registry_Access; App : Application_Access := null; Name : Unbounded_String; URI : Unbounded_String; Config : ASF.Applications.Config; Self : Module_Access := null; Listeners : Util.Listeners.List; end record; -- Map to find a module from its name or its URI package Module_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Module_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Module_Registry is limited record Config : ASF.Applications.Config; Name_Map : Module_Maps.Map; URI_Map : Module_Maps.Map; end record; type Module_Manager is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with record Module : Module_Access := null; end record; type Pool_Module is new Module with record D : Natural; end record; type Session_Module is new Module with record P : Natural; end record; use Util.Log; -- The logger (used by the generic Get function). Log : constant Loggers.Logger := Loggers.Create ("AWA.Modules"); end AWA.Modules;
Declare Get_Config function with the Module_Manager type
Declare Get_Config function with the Module_Manager type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ea600dac70698601014c1b83c7d8fedc493a4cfd
regtests/security-oauth-jwt-tests.adb
regtests/security-oauth-jwt-tests.adb
----------------------------------------------------------------------- -- Security-oayth-jwt-tests - Unit tests for JSON Web Token -- 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.Calendar.Formatting; with Util.Test_Caller; package body Security.OAuth.JWT.Tests is package Caller is new Util.Test_Caller (Test, "Security.OAuth.JWT"); -- A JWT token returned by Google+. K : constant String := "eyJhbGciOiJSUzI1NiIsImtpZCI6IjVmOTBlMWExMGE4YzgwZWJhZWNmYzM4NzBjZDl" & "lMGVhMGI3ZDVmZGMifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXRfaGFzaCI6Im9Ka19EYnFvb1" & "FVc0FhY3k2cnkxeHciLCJhdWQiOiI4NzI2NTU5OTQwMTQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJz" & "dWIiOiIxMDgzNjA3MDMwOTk3MDg5Nzg4NzAiLCJlbWFpbF92ZXJpZmllZCI6InRydWUiLCJhenAiOiI4NzI2NT" & "U5OTQwMTQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJlbWFpbCI6InN0ZXBoYW5lLmNhcnJlekBnbWFp" & "bC5jb20iLCJpYXQiOjEzNjg5NjgyMzMsImV4cCI6MTM2ODk3MjEzM30.UL1qp2wmleV-ED2A_hlqgDLIGgJB3f" & "_N7fiz1CgttJcwbmMVwhag3ox2WE9C1KwXhrjwT8eigZ0WkDys5WO1dYs2G1QbDZPnsYYMyHK9XpycaDMEKtVZ" & "C4C6DkB1SrBHbN0Tv6ExWpszzp1JEL8nZnHd3T_AA3paqONnkvQw_yo"; procedure Test_Operation (T : in out Test) is R : Token; begin R := Decode (K); Util.Tests.Assert_Equals (T, Value, Get (R), "Extraction failed"); end Test_Operation; procedure Test_Time_Operation (T : in out Test) is R : Token; begin R := Decode (K); Util.Tests.Assert_Equals (T, Value, Ada.Calendar.Formatting.Image (Get (R)), "Extraction failed"); end Test_Time_Operation; procedure Test_Get_Issuer is new Test_Operation (Get_Issuer, "accounts.google.com"); procedure Test_Get_Audience is new Test_Operation (Get_Audience, "872655994014.apps.googleusercontent.com"); procedure Test_Get_Subject is new Test_Operation (Get_Subject, "108360703099708978870"); procedure Test_Get_Authorized_Presenters is new Test_Operation (Get_Authorized_Presenters, "872655994014.apps.googleusercontent.com"); procedure Test_Get_Expiration is new Test_Time_Operation (Get_Expiration, "2013-05-19 14:02:13"); procedure Test_Get_Issued_At is new Test_Time_Operation (Get_Issued_At, "2013-05-19 12:57:13"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Decode", Test_Get_Issuer'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Issuer", Test_Get_Issuer'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Audience", Test_Get_Audience'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Subject", Test_Get_Subject'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Authorized_Presenters", Test_Get_Authorized_Presenters'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Expiration", Test_Get_Expiration'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Authentication_Time", Test_Get_Issued_At'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Decode (error)", Test_Decode_Error'Access); end Add_Tests; -- ------------------------------ -- Test Decode operation with errors. -- ------------------------------ procedure Test_Decode_Error (T : in out Test) is K : constant String := "eyJhbxGciOiJSUzI1NiIsImtpZCI6IjVmOTBlMWExMGE4YzgwZWJhZWNmYzM4NzBjZDl" & "lMGVhMGI3ZDVmZGMifQ.eyJpc3xMiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXRfaGFzaCI6Im9Ka19EYnFvb1" & "FVc0FhY3k2cnkxeHciLCJhdWQiOiI4NzI2NTU5OTQwMTQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJz" & "dWIiOiIxMDgzNjA3MDMwOTk3MDg5Nzg4NzAiLCJlbWFpbF92ZXJpZmllZCI6InRydWUiLCJhenAiOiI4NzI2NT" & "U5OTQwMTQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJlbWFpbCI6InN0ZXBoYW5lLmNhcnJlekBnbWFp" & "bC5jb20iLCJpYXQiOjEzNjg5NjgyMzMsImV4cCI6MTM2ODk3MjEzM30.UL1qp2wmleV-ED2A_hlqgDLIGgJB3f" & "_N7fiz1CgttJcwbmMVwhag3ox2WE9C1KwXhrjwT8eigZ0WkDys5WO1dYs2G1QbDZPnsYYMyHK9XpycaDMEKtVZ" & "C4C6DkB1SrBHbN0Tv6ExWpszzp1JEL8nZnHd3T_AA3paqONnkvQw_yx"; R : Token; begin R := Decode (K); T.Fail ("No exception raised"); T.Assert (False, "Bad"); exception when Invalid_Token => null; end Test_Decode_Error; end Security.OAuth.JWT.Tests;
----------------------------------------------------------------------- -- Security-oayth-jwt-tests - Unit tests for JSON Web Token -- Copyright (C) 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Formatting; with Util.Test_Caller; package body Security.OAuth.JWT.Tests is package Caller is new Util.Test_Caller (Test, "Security.OAuth.JWT"); -- A JWT token returned by Google+. K : constant String := "eyJhbGciOiJSUzI1NiIsImtpZCI6IjVmOTBlMWExMGE4YzgwZWJhZWNmYzM4NzBjZDl" & "lMGVhMGI3ZDVmZGMifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXRfaGFzaCI6Im9Ka19EYnFvb1" & "FVc0FhY3k2cnkxeHciLCJhdWQiOiI4NzI2NTU5OTQwMTQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJz" & "dWIiOiIxMDgzNjA3MDMwOTk3MDg5Nzg4NzAiLCJlbWFpbF92ZXJpZmllZCI6InRydWUiLCJhenAiOiI4NzI2NT" & "U5OTQwMTQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJlbWFpbCI6InN0ZXBoYW5lLmNhcnJlekBnbWFp" & "bC5jb20iLCJpYXQiOjEzNjg5NjgyMzMsImV4cCI6MTM2ODk3MjEzM30.UL1qp2wmleV-ED2A_hlqgDLIGgJB3f" & "_N7fiz1CgttJcwbmMVwhag3ox2WE9C1KwXhrjwT8eigZ0WkDys5WO1dYs2G1QbDZPnsYYMyHK9XpycaDMEKtVZ" & "C4C6DkB1SrBHbN0Tv6ExWpszzp1JEL8nZnHd3T_AA3paqONnkvQw_yo"; procedure Test_Operation (T : in out Test) is R : Token; begin R := Decode (K); Util.Tests.Assert_Equals (T, Value, Get (R), "Extraction failed"); end Test_Operation; procedure Test_Time_Operation (T : in out Test) is R : Token; begin R := Decode (K); Util.Tests.Assert_Equals (T, Value, Ada.Calendar.Formatting.Image (Get (R)), "Extraction failed"); end Test_Time_Operation; procedure Test_Get_Issuer is new Test_Operation (Get_Issuer, "accounts.google.com"); procedure Test_Get_Audience is new Test_Operation (Get_Audience, "872655994014.apps.googleusercontent.com"); procedure Test_Get_Subject is new Test_Operation (Get_Subject, "108360703099708978870"); procedure Test_Get_Authorized_Presenters is new Test_Operation (Get_Authorized_Presenters, "872655994014.apps.googleusercontent.com"); procedure Test_Get_Expiration is new Test_Time_Operation (Get_Expiration, "2013-05-19 14:02:13"); procedure Test_Get_Issued_At is new Test_Time_Operation (Get_Issued_At, "2013-05-19 12:57:13"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Decode", Test_Get_Issuer'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Issuer", Test_Get_Issuer'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Audience", Test_Get_Audience'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Subject", Test_Get_Subject'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Authorized_Presenters", Test_Get_Authorized_Presenters'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Expiration", Test_Get_Expiration'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Get_Authentication_Time", Test_Get_Issued_At'Access); Caller.Add_Test (Suite, "Test Security.OAuth.JWT.Decode (error)", Test_Decode_Error'Access); end Add_Tests; -- ------------------------------ -- Test Decode operation with errors. -- ------------------------------ procedure Test_Decode_Error (T : in out Test) is K : constant String := "eyJhbxGciOiJSUzI1NiIsImtpZCI6IjVmOTBlMWExMGE4YzgwZWJhZWNmYzM4NzBjZDl" & "lMGVhMGI3ZDVmZGMifQ.eyJpc3xMiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXRfaGFzaCI6Im9Ka19EYnFvb1" & "FVc0FhY3k2cnkxeHciLCJhdWQiOiI4NzI2NTU5OTQwMTQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJz" & "dWIiOiIxMDgzNjA3MDMwOTk3MDg5Nzg4NzAiLCJlbWFpbF92ZXJpZmllZCI6InRydWUiLCJhenAiOiI4NzI2NT" & "U5OTQwMTQuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJlbWFpbCI6InN0ZXBoYW5lLmNhcnJlekBnbWFp" & "bC5jb20iLCJpYXQiOjEzNjg5NjgyMzMsImV4cCI6MTM2ODk3MjEzM30.UL1qp2wmleV-ED2A_hlqgDLIGgJB3f" & "_N7fiz1CgttJcwbmMVwhag3ox2WE9C1KwXhrjwT8eigZ0WkDys5WO1dYs2G1QbDZPnsYYMyHK9XpycaDMEKtVZ" & "C4C6DkB1SrBHbN0Tv6ExWpszzp1JEL8nZnHd3T_AA3paqONnkvQw_yx"; R : Token; pragma Unreferenced (R); begin R := Decode (K); T.Fail ("No exception raised"); T.Assert (False, "Bad"); exception when Invalid_Token => null; end Test_Decode_Error; end Security.OAuth.JWT.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-security
319aa8ed154a0106f11888edd288143a87279956
src/util-measures.ads
src/util-measures.ads
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Ada.Containers; with Ada.Finalization; with Util.Streams.Texts; -- The <b>Measures</b> package defines utility types and functions to make -- performance measurements in an Ada application. It is designed to be used -- for production and multi-threaded environments. -- -- A measurement point starts by the creation of a <b>Stamp</b> variable -- and ends at the next call to <b>Report</b> on that variable. -- -- declare -- M : Stamp; -- begin -- ... -- Util.Measures.Report (M, "Request for X"); -- end; -- -- Measures are collected in a <b>Measure_Set</b> which collects the number of -- times each measure was made and the sum of their duration. -- Measures can be written in an XML file once they are collected. package Util.Measures is type Unit_Type is (Seconds, Milliseconds, Microseconds, Nanoseconds); -- ------------------------------ -- Measure Set -- ------------------------------ -- The measure set represent a collection of measures each of them being -- associated with a same name. Several measure sets can be created to -- collect different kinds of runtime information. The measure set can be -- set on a per-thread data and every call to <b>Report</b> will be -- associated with that measure set. -- -- Measure set are thread-safe. type Measure_Set is limited private; type Measure_Set_Access is access all Measure_Set; -- Disable collecting measures on the measure set. procedure Disable (Measures : in out Measure_Set); -- Enable collecting measures on the measure set. procedure Enable (Measures : in out Measure_Set); -- Set the per-thread measure set. procedure Set_Current (Measures : in Measure_Set_Access); -- Get the per-thread measure set. function Get_Current return Measure_Set_Access; -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class); -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type); -- Dump an XML result with the measures in a file. procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String); -- ------------------------------ -- Stamp -- ------------------------------ -- The stamp marks the beginning of a measure when the variable of such -- type is declared. The measure represents the time that elapsed between -- the stamp creation and when the <b>Report</b> method is called. type Stamp is limited private; -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. procedure Report (S : in out Stamp; Title : in String); -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String); -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds); private type String_Access is access String; type Stamp is limited record Start : Ada.Calendar.Time := Ada.Calendar.Clock; end record; type Measure; type Measure_Access is access Measure; type Measure is limited record Next : Measure_Access; Time : Duration; Count : Positive; Name : String_Access; end record; type Buckets_Type is array (Ada.Containers.Hash_Type range <>) of Measure_Access; type Buckets_Access is access all Buckets_Type; -- To reduce contention we only protect insertion and updates of measures. -- To write the measure set, we steal the buckets and force the next call -- to <b>Add</b> to reallocate the buckets. protected type Measure_Data is -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time); -- Add the measure procedure Add (Title : in String; D : in Duration); private Start : Ada.Calendar.Time := Ada.Calendar.Clock; Buckets : Buckets_Access; end Measure_Data; type Measure_Set is new Ada.Finalization.Limited_Controlled with record Enabled : Boolean := True; pragma Atomic (Enabled); Data : Measure_Data; end record; -- Finalize the measures and release the storage. overriding procedure Finalize (Measures : in out Measure_Set); end Util.Measures;
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Ada.Containers; with Ada.Finalization; with Util.Streams.Texts; -- The <b>Measures</b> package defines utility types and functions to make -- performance measurements in an Ada application. It is designed to be used -- for production and multi-threaded environments. -- -- A measurement point starts by the creation of a <b>Stamp</b> variable -- and ends at the next call to <b>Report</b> on that variable. -- -- declare -- M : Stamp; -- begin -- ... -- Util.Measures.Report (M, "Request for X"); -- end; -- -- Measures are collected in a <b>Measure_Set</b> which collects the number of -- times each measure was made and the sum of their duration. -- Measures can be written in an XML file once they are collected. package Util.Measures is type Unit_Type is (Seconds, Milliseconds, Microseconds, Nanoseconds); -- ------------------------------ -- Measure Set -- ------------------------------ -- The measure set represent a collection of measures each of them being -- associated with a same name. Several measure sets can be created to -- collect different kinds of runtime information. The measure set can be -- set on a per-thread data and every call to <b>Report</b> will be -- associated with that measure set. -- -- Measure set are thread-safe. type Measure_Set is limited private; type Measure_Set_Access is access all Measure_Set; -- Disable collecting measures on the measure set. procedure Disable (Measures : in out Measure_Set); -- Enable collecting measures on the measure set. procedure Enable (Measures : in out Measure_Set); -- Set the per-thread measure set. procedure Set_Current (Measures : in Measure_Set_Access); -- Get the per-thread measure set. function Get_Current return Measure_Set_Access; -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class); -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type); -- Dump an XML result with the measures in a file. procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String); -- ------------------------------ -- Stamp -- ------------------------------ -- The stamp marks the beginning of a measure when the variable of such -- type is declared. The measure represents the time that elapsed between -- the stamp creation and when the <b>Report</b> method is called. type Stamp is limited private; -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1); -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1); -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds); private type String_Access is access String; type Stamp is limited record Start : Ada.Calendar.Time := Ada.Calendar.Clock; end record; type Measure; type Measure_Access is access Measure; type Measure is limited record Next : Measure_Access; Time : Duration; Count : Positive; Name : String_Access; end record; type Buckets_Type is array (Ada.Containers.Hash_Type range <>) of Measure_Access; type Buckets_Access is access all Buckets_Type; -- To reduce contention we only protect insertion and updates of measures. -- To write the measure set, we steal the buckets and force the next call -- to <b>Add</b> to reallocate the buckets. protected type Measure_Data is -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time); -- Add the measure procedure Add (Title : in String; D : in Duration; Count : in Positive := 1); private Start : Ada.Calendar.Time := Ada.Calendar.Clock; Buckets : Buckets_Access; end Measure_Data; type Measure_Set is new Ada.Finalization.Limited_Controlled with record Enabled : Boolean := True; pragma Atomic (Enabled); Data : Measure_Data; end record; -- Finalize the measures and release the storage. overriding procedure Finalize (Measures : in out Measure_Set); end Util.Measures;
Add an optional Count parameter to each Report procedure
Add an optional Count parameter to each Report procedure
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
1d036fae01c0606a405f29739c45bf4baf701f48
matp/src/mat-commands.ads
matp/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- 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); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Events command. -- Print the probe events. procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Event command. -- Print the probe event with the stack frame. procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Info command to print symmary information about the program. procedure Info_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- 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); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Events command. -- Print the probe events. procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Event command. -- Print the probe event with the stack frame. procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Info command to print symmary information about the program. procedure Info_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Timeline command. -- Identify the interesting timeline groups in the events and display them. procedure Timeline_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Declare the Timeline_Command procedure
Declare the Timeline_Command procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
5882d49482db7178a60b96b6ce598def08147188
awa/awaunit/awa-tests-helpers.adb
awa/awaunit/awa-tests-helpers.adb
----------------------------------------------------------------------- -- awa-tests-helpers - Helpers for AWA unit tests -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Tests.Helpers is -- ------------------------------ -- Extract from the Location header the part that is after the given base string. -- If the Location header does not start with the base string, returns the empty -- string. -- ------------------------------ function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return String is R : constant String := Reply.Get_Header ("Location"); begin if R'Length < Base'Length then return ""; elsif R (R'First .. R'First + Base'Length - 1) /= Base then return ""; else return R (R'First + Base'Length .. R'Last); end if; end Extract_Redirect; function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Extract_Redirect (Reply, Base)); end Extract_Redirect; end AWA.Tests.Helpers;
----------------------------------------------------------------------- -- awa-tests-helpers - Helpers for AWA unit tests -- Copyright (C) 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; package body AWA.Tests.Helpers is -- ------------------------------ -- Extract from the Location header the part that is after the given base string. -- If the Location header does not start with the base string, returns the empty -- string. -- ------------------------------ function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return String is R : constant String := Reply.Get_Header ("Location"); begin if R'Length < Base'Length then return ""; elsif R (R'First .. R'First + Base'Length - 1) /= Base then return ""; else return R (R'First + Base'Length .. R'Last); end if; end Extract_Redirect; function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class; Base : in String) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Extract_Redirect (Reply, Base)); end Extract_Redirect; -- ------------------------------ -- Extract from the response content a link with a given title. -- ------------------------------ function Extract_Link (Content : in String; Title : in String) return String is use GNAT.Regpat; Pattern : constant String := " href=""([a-zA-Z0-9/]+)"">" & Title & "</a>"; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern); Result : GNAT.Regpat.Match_Array (0 .. 1); begin Match (Regexp, Content, Result); if Result (1) = GNAT.Regpat.No_Match then return ""; end if; return Content (Result (1).First .. Result (1).Last); end Extract_Link; end AWA.Tests.Helpers;
Implement the Extract_Link function
Implement the Extract_Link function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f2bb463abd652d287b0650919364dec76ea5c198
awa/src/awa-users-beans.adb
awa/src/awa-users-beans.adb
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user 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 ASF.Principals; with ASF.Sessions; with ASF.Events.Actions; with ASF.Contexts.Faces; with ASF.Cookies; with AWA.Users.Principals; package body AWA.Users.Beans is use AWA.Users.Models; -- ------------------------------ -- Action to register a user -- ------------------------------ procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); end Register_User; -- ------------------------------ -- Action to verify the user after the registration -- ------------------------------ procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), User => User, IpAddr => "", Session => Session); Data.Set_Session_Principal (User, Session); Outcome := To_Unbounded_String ("success"); end Verify_User; -- ------------------------------ -- Action to trigger the lost password email process. -- ------------------------------ procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); end Lost_Password; -- ------------------------------ -- Action to validate the reset password key and set a new password. -- ------------------------------ procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; User : in AWA.Users.Models.User_Ref; Sess : in AWA.Users.Models.Session_Ref) is pragma Unreferenced (Data); Principal : constant Principals.Principal_Access := Principals.Create (User, Sess); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (User, Session); end Authenticate_User; -- ------------------------------ -- Logout the user and closes the session. -- ------------------------------ procedure Logout_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is use type ASF.Principals.Principal_Access; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False); begin Outcome := To_Unbounded_String ("success"); -- If there is no session, we are done. if not Session.Is_Valid then return; end if; declare Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal; begin if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then declare P : constant AWA.Users.Principals.Principal_Access := AWA.Users.Principals.Principal'Class (Principal.all)'Access; begin Data.Manager.Close_Session (Id => P.Get_Session_Identifier); end; end if; Session.Invalidate; end; -- Remove the session cookie. declare C : ASF.Cookies.Cookie := ASF.Cookies.Create ("SID", ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end; end Logout_User; -- ------------------------------ -- Create an authenticate bean. -- ------------------------------ function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Module.Get_User_Manager; return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); package Logout_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Logout_User, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access, Logout_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = EMAIL_ATTR then return Util.Beans.Objects.To_Object (From.Email); elsif Name = PASSWORD_ATTR then return Util.Beans.Objects.To_Object (From.Password); elsif Name = FIRST_NAME_ATTR then return Util.Beans.Objects.To_Object (From.First_Name); elsif Name = LAST_NAME_ATTR then return Util.Beans.Objects.To_Object (From.Last_Name); elsif Name = KEY_ATTR then return Util.Beans.Objects.To_Object (From.Access_Key); 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 Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = EMAIL_ATTR then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = PASSWORD_ATTR then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = FIRST_NAME_ATTR then From.First_Name := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = LAST_NAME_ATTR then From.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = KEY_ATTR then From.Access_Key := 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 Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; end AWA.Users.Beans;
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user 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.Log.Loggers; with ASF.Principals; with ASF.Sessions; with ASF.Events.Actions; with ASF.Contexts.Faces; with ASF.Cookies; with ASF.Applications.Messages.Factory; with AWA.Users.Principals; package body AWA.Users.Beans is use Util.Log; use AWA.Users.Models; Log : constant Loggers.Logger := Loggers.Create ("AWA.Users.Beans"); -- ------------------------------ -- Action to register a user -- ------------------------------ procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); end Register_User; -- ------------------------------ -- Action to verify the user after the registration -- ------------------------------ procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), User => User, IpAddr => "", Session => Session); Data.Set_Session_Principal (User, Session); Outcome := To_Unbounded_String ("success"); end Verify_User; -- ------------------------------ -- Action to trigger the lost password email process. -- ------------------------------ procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); end Lost_Password; -- ------------------------------ -- Action to validate the reset password key and set a new password. -- ------------------------------ procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; User : in AWA.Users.Models.User_Ref; Sess : in AWA.Users.Models.Session_Ref) is pragma Unreferenced (Data); Principal : constant Principals.Principal_Access := Principals.Create (User, Sess); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (User, Session); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.login_signup_fail_message"); end Authenticate_User; -- ------------------------------ -- Logout the user and closes the session. -- ------------------------------ procedure Logout_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is use type ASF.Principals.Principal_Access; Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False); begin Outcome := To_Unbounded_String ("success"); -- If there is no session, we are done. if not Session.Is_Valid then return; end if; declare Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal; begin if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then declare P : constant AWA.Users.Principals.Principal_Access := AWA.Users.Principals.Principal'Class (Principal.all)'Access; begin Data.Manager.Close_Session (Id => P.Get_Session_Identifier); exception when others => Log.Error ("Exception when closing user session..."); end; end if; Session.Invalidate; end; -- Remove the session cookie. declare C : ASF.Cookies.Cookie := ASF.Cookies.Create ("SID", ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end; end Logout_User; -- ------------------------------ -- Create an authenticate bean. -- ------------------------------ function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Module.Get_User_Manager; return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); package Logout_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Logout_User, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access, Logout_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = EMAIL_ATTR then return Util.Beans.Objects.To_Object (From.Email); elsif Name = PASSWORD_ATTR then return Util.Beans.Objects.To_Object (From.Password); elsif Name = FIRST_NAME_ATTR then return Util.Beans.Objects.To_Object (From.First_Name); elsif Name = LAST_NAME_ATTR then return Util.Beans.Objects.To_Object (From.Last_Name); elsif Name = KEY_ATTR then return Util.Beans.Objects.To_Object (From.Access_Key); 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 Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = EMAIL_ATTR then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = PASSWORD_ATTR then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = FIRST_NAME_ATTR then From.First_Name := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = LAST_NAME_ATTR then From.Last_Name := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = KEY_ATTR then From.Access_Key := 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 Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; end AWA.Users.Beans;
Add a global error message if the user authentication failed.
Add a global error message if the user authentication failed.
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a264d13100be8ac12c2d816d4b0028d813d547b5
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; package MAT.Expressions is type Resolver_Type is limited interface; type Resolver_Type_Access is access all Resolver_Type'Class; -- Find the region that matches the given name. function Find_Region (Resolver : in Resolver_Type; Name : in String) return MAT.Memory.Region_Info is abstract; -- Find the symbol in the symbol table and return the start and end address. function Find_Symbol (Resolver : in Resolver_Type; Name : in String) return MAT.Memory.Region_Info is abstract; type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_REGION, INSIDE_DIRECT_REGION, 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.Event_Id_Type; Max : in MAT.Events.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.Probe_Index_Type) return Expression_Type; -- Create an expression node to keep allocation events which don't have any associated free. function Create_No_Free 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.Target_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String; Resolver : in Resolver_Type_Access) 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 => 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 | N_IN_FUNC | N_IN_FUNC_DIRECT => 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.Event_Id_Type; Max_Event : MAT.Events.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.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.Target_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; package MAT.Expressions is type Resolver_Type is limited interface; type Resolver_Type_Access is access all Resolver_Type'Class; -- Find the region that matches the given name. function Find_Region (Resolver : in Resolver_Type; Name : in String) return MAT.Memory.Region_Info is abstract; -- Find the symbol in the symbol table and return the start and end address. function Find_Symbol (Resolver : in Resolver_Type; Name : in String) return MAT.Memory.Region_Info is abstract; -- Get the start time for the tick reference. function Get_Start_Time (Resolver : in Resolver_Type) return MAT.Types.Target_Tick_Ref is abstract; type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_REGION, INSIDE_DIRECT_REGION, 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.Event_Id_Type; Max : in MAT.Events.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.Probe_Index_Type) return Expression_Type; -- Create an expression node to keep allocation events which don't have any associated free. function Create_No_Free 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.Target_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String; Resolver : in Resolver_Type_Access) 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 => 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 | N_IN_FUNC | N_IN_FUNC_DIRECT => 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.Event_Id_Type; Max_Event : MAT.Events.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.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.Target_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;
Declare the Get_Start_Time abstract function for the Resolver_Type
Declare the Get_Start_Time abstract function for the Resolver_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ec9594bdf26c1d6a71b30dd376f746f0d3999a6f
src/gen-commands-model.ads
src/gen-commands-model.ads
----------------------------------------------------------------------- -- gen-commands-model -- Model creation command for dynamo -- 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. ----------------------------------------------------------------------- package Gen.Commands.Model is -- ------------------------------ -- Model Creation Command -- ------------------------------ -- This command adds a model file to the web application. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Model;
----------------------------------------------------------------------- -- gen-commands-model -- Model creation command for dynamo -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Model is -- ------------------------------ -- Model Creation Command -- ------------------------------ -- This command adds a model file to the web application. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Model;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
ced823a4f44608eeb878fb5b190ed798152f52be
src/gen-model-packages.adb
src/gen-model-packages.adb
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- 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; with Ada.Strings.Maps; with Gen.Utils; with Gen.Model.Enums; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Beans; with Util.Strings; with Util.Strings.Transforms; with Util.Log.Loggers; package body Gen.Model.Packages is use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Packages"); -- ------------------------------ -- 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 Package_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Pkg_Name); elsif Name = "package" then return Util.Beans.Objects.To_Object (From.Base_Name); elsif Name = "tables" then return From.Tables_Bean; elsif Name = "enums" then return From.Enums_Bean; elsif Name = "queries" then return From.Queries_Bean; elsif Name = "usedTypes" then return From.Used; elsif Name = "useCalendarTime" then return Util.Beans.Objects.To_Object (From.Uses_Calendar_Time); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Register the declaration of the given enum in the model. -- ------------------------------ procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class) is Name : constant String := Enum.Get_Name; begin Log.Info ("Registering enum {0}", Name); O.Register_Package (Enum.Pkg_Name, Enum.Package_Def); if Enum.Package_Def.Enums.Find (Name) /= null then raise Name_Exist with "Enum '" & Name & "' already defined"; end if; Enum.Package_Def.Enums.Append (Enum.all'Access); O.Enums.Append (Enum.all'Access); Gen.Model.Mappings.Register_Type (To_String (Enum.Name), Enum.all'Access, Gen.Model.Mappings.T_ENUM); end Register_Enum; -- ------------------------------ -- Register the declaration of the given table in the model. -- ------------------------------ procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class) is Name : constant String := Table.Get_Name; begin Log.Info ("Registering table {0}", Name); O.Register_Package (Table.Pkg_Name, Table.Package_Def); if Table.Package_Def.Tables.Find (Name) /= null then raise Name_Exist with "Table '" & Name & "' already defined"; end if; Table.Package_Def.Tables.Append (Table.all'Access); O.Tables.Append (Table.all'Access); end Register_Table; -- ------------------------------ -- Register the declaration of the given query in the model. -- ------------------------------ procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_Definition'Class) is begin O.Register_Package (Table.Pkg_Name, Table.Package_Def); Table.Package_Def.Queries.Append (Table.all'Access); O.Queries.Append (Table.all'Access); end Register_Query; -- ------------------------------ -- Register the declaration of the given bean in the model. -- ------------------------------ procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class) is begin O.Register_Package (Bean.Pkg_Name, Bean.Package_Def); Bean.Package_Def.Beans.Append (Bean.all'Access); O.Queries.Append (Bean.all'Access); end Register_Bean; -- ------------------------------ -- Register or find the package knowing its name -- ------------------------------ procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access) is Pkg : constant String := Util.Strings.Transforms.To_Upper_Case (To_String (Name)); Key : constant Unbounded_String := To_Unbounded_String (Pkg); Pos : constant Package_Map.Cursor := O.Packages.Find (Key); begin if not Package_Map.Has_Element (Pos) then declare Map : Ada.Strings.Maps.Character_Mapping; Base_Name : Unbounded_String; begin Map := Ada.Strings.Maps.To_Mapping (From => ".", To => "-"); Base_Name := Translate (Name, Map); Result := new Package_Definition; Result.Pkg_Name := Name; Result.Tables_Bean := Util.Beans.Objects.To_Object (Result.Tables'Access, Util.Beans.Objects.STATIC); Util.Strings.Transforms.To_Lower_Case (To_String (Base_Name), Result.Base_Name); O.Packages.Insert (Key, Result); Log.Debug ("Ada package '{0}' registered", Name); end; else Result := Package_Map.Element (Pos); end if; end Register_Package; -- ------------------------------ -- Returns True if the model contains at least one package. -- ------------------------------ function Has_Packages (O : in Model_Definition) return Boolean is begin return not O.Packages.Is_Empty; end Has_Packages; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Package_Definition) is use Gen.Model.Tables; procedure Prepare_Table (Table : in Table_Definition_Access); procedure Prepare_Tables (Tables : in Table_List.List_Definition); Used_Types : Gen.Utils.String_Set.Set; T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Used_Types'Unchecked_Access; procedure Prepare_Table (Table : in Table_Definition_Access) is C : Column_List.Cursor := Table.Members.First; begin Table.Prepare; -- Walk the columns to get their type. while Column_List.Has_Element (C) loop declare Col : constant Column_Definition_Access := Column_List.Element (C); T : constant String := To_String (Col.Type_Name); Name : constant String := Gen.Utils.Get_Package_Name (T); begin if not Col.Is_Basic_Type and Name'Length > 0 and Name /= O.Pkg_Name then Used_Types.Include (To_Unbounded_String (Name)); elsif T = "Time" or T = "Date" or T = "Timestamp" or T = "Nullable_Time" then O.Uses_Calendar_Time := True; end if; end; Column_List.Next (C); end loop; end Prepare_Table; procedure Prepare_Tables (Tables : in Table_List.List_Definition) is Table_Iter : Table_List.Cursor := Tables.First; begin while Table_List.Has_Element (Table_Iter) loop declare Table : constant Definition_Access := Table_List.Element (Table_Iter); begin if Table.all in Table_Definition'Class then Prepare_Table (Table_Definition_Access (Table)); else Table.Prepare; end if; end; Table_List.Next (Table_Iter); end loop; end Prepare_Tables; begin Log.Info ("Preparing package {0}", O.Pkg_Name); O.Used := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Used_Types.Row := 0; O.Used_Types.Values.Clear; O.Uses_Calendar_Time := False; O.Enums.Sort; O.Queries.Sort; Prepare_Tables (O.Enums); Prepare_Tables (O.Tables); Prepare_Tables (O.Queries); declare P : Gen.Utils.String_Set.Cursor := Used_Types.First; begin while Gen.Utils.String_Set.Has_Element (P) loop declare Name : constant Unbounded_String := Gen.Utils.String_Set.Element (P); begin Log.Info ("with {0}", Name); O.Used_Types.Values.Append (Util.Beans.Objects.To_Object (Name)); end; Gen.Utils.String_Set.Next (P); end loop; end; end Prepare; -- ------------------------------ -- Initialize the package instance -- ------------------------------ overriding procedure Initialize (O : in out Package_Definition) is use Util.Beans.Objects; begin O.Enums_Bean := Util.Beans.Objects.To_Object (O.Enums'Unchecked_Access, STATIC); O.Tables_Bean := Util.Beans.Objects.To_Object (O.Tables'Unchecked_Access, STATIC); O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access, STATIC); O.Used := Util.Beans.Objects.To_Object (O.Used_Types'Unchecked_Access, STATIC); end Initialize; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : List_Object) return Natural is begin Log.Debug ("Length {0}", Natural'Image (Natural (From.Values.Length))); return Natural (From.Values.Length); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural) is begin Log.Debug ("Setting row {0}", Natural'Image (Index)); From.Row := Index; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : List_Object) return Util.Beans.Objects.Object is begin Log.Debug ("Getting row {0}", Natural'Image (From.Row)); return From.Values.Element (From.Row - 1); end Get_Row; -- ------------------------------ -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); pragma Unreferenced (Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- 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 Model_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tables" then return From.Tables_Bean; elsif Name = "dirname" then return Util.Beans.Objects.To_Object (From.Dir_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. -- ------------------------------ procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String) is begin O.Dir_Name := To_Unbounded_String (Target_Dir); O.DB_Name := To_Unbounded_String (Model_Dir); end Set_Dirname; -- ------------------------------ -- Get the directory name associated with the model. -- ------------------------------ function Get_Dirname (O : in Model_Definition) return String is begin return To_String (O.Dir_Name); end Get_Dirname; -- ------------------------------ -- Get the directory name which contains the model. -- ------------------------------ function Get_Model_Directory (O : in Model_Definition) return String is begin return To_String (O.DB_Name); end Get_Model_Directory; -- ------------------------------ -- Initialize the model definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Model_Definition) is T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Tables'Unchecked_Access; begin O.Tables_Bean := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Dir_Name := To_Unbounded_String ("src"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Model_Definition) is Iter : Package_Cursor := O.Packages.First; begin while Has_Element (Iter) loop Element (Iter).Prepare; Next (Iter); end loop; O.Tables.Sort; end Prepare; -- ------------------------------ -- Get the first package of the model definition. -- ------------------------------ function First (From : Model_Definition) return Package_Cursor is begin return From.Packages.First; end First; -- ------------------------------ -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. -- ------------------------------ procedure Register_Type (O : in out Model_Definition; From : in String; To : in String) is begin null; end Register_Type; end Gen.Model.Packages;
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- 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; with Ada.Strings.Maps; with Gen.Utils; with Gen.Model.Enums; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Beans; with Util.Strings; with Util.Strings.Transforms; with Util.Log.Loggers; package body Gen.Model.Packages is use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Packages"); -- ------------------------------ -- 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 Package_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Pkg_Name); elsif Name = "package" then return Util.Beans.Objects.To_Object (From.Base_Name); elsif Name = "tables" then return From.Tables_Bean; elsif Name = "enums" then return From.Enums_Bean; elsif Name = "queries" then return From.Queries_Bean; elsif Name = "usedTypes" then return From.Used; elsif Name = "useCalendarTime" then return Util.Beans.Objects.To_Object (From.Uses_Calendar_Time); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Register the declaration of the given enum in the model. -- ------------------------------ procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class) is Name : constant String := Enum.Get_Name; begin Log.Info ("Registering enum {0}", Name); O.Register_Package (Enum.Pkg_Name, Enum.Package_Def); if Enum.Package_Def.Enums.Find (Name) /= null then raise Name_Exist with "Enum '" & Name & "' already defined"; end if; Enum.Package_Def.Enums.Append (Enum.all'Access); O.Enums.Append (Enum.all'Access); Gen.Model.Mappings.Register_Type (To_String (Enum.Name), Enum.all'Access, Gen.Model.Mappings.T_ENUM); end Register_Enum; -- ------------------------------ -- Register the declaration of the given table in the model. -- ------------------------------ procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class) is Name : constant String := Table.Get_Name; begin Log.Info ("Registering table {0}", Name); O.Register_Package (Table.Pkg_Name, Table.Package_Def); if Table.Package_Def.Tables.Find (Name) /= null then raise Name_Exist with "Table '" & Name & "' already defined"; end if; Table.Package_Def.Tables.Append (Table.all'Access); O.Tables.Append (Table.all'Access); end Register_Table; -- ------------------------------ -- Register the declaration of the given query in the model. -- ------------------------------ procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_Definition'Class) is begin O.Register_Package (Table.Pkg_Name, Table.Package_Def); Table.Package_Def.Queries.Append (Table.all'Access); O.Queries.Append (Table.all'Access); end Register_Query; -- ------------------------------ -- Register the declaration of the given bean in the model. -- ------------------------------ procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class) is begin O.Register_Package (Bean.Pkg_Name, Bean.Package_Def); Bean.Package_Def.Beans.Append (Bean.all'Access); O.Queries.Append (Bean.all'Access); end Register_Bean; -- ------------------------------ -- Register or find the package knowing its name -- ------------------------------ procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access) is Pkg : constant String := Util.Strings.Transforms.To_Upper_Case (To_String (Name)); Key : constant Unbounded_String := To_Unbounded_String (Pkg); Pos : constant Package_Map.Cursor := O.Packages.Find (Key); begin if not Package_Map.Has_Element (Pos) then declare Map : Ada.Strings.Maps.Character_Mapping; Base_Name : Unbounded_String; begin Map := Ada.Strings.Maps.To_Mapping (From => ".", To => "-"); Base_Name := Translate (Name, Map); Result := new Package_Definition; Result.Pkg_Name := Name; Result.Tables_Bean := Util.Beans.Objects.To_Object (Result.Tables'Access, Util.Beans.Objects.STATIC); Util.Strings.Transforms.To_Lower_Case (To_String (Base_Name), Result.Base_Name); O.Packages.Insert (Key, Result); Log.Debug ("Ada package '{0}' registered", Name); end; else Result := Package_Map.Element (Pos); end if; end Register_Package; -- ------------------------------ -- Returns True if the model contains at least one package. -- ------------------------------ function Has_Packages (O : in Model_Definition) return Boolean is begin return not O.Packages.Is_Empty; end Has_Packages; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Package_Definition) is use Gen.Model.Tables; procedure Prepare_Table (Table : in Table_Definition_Access); procedure Prepare_Tables (Tables : in Table_List.List_Definition); Used_Types : Gen.Utils.String_Set.Set; T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Used_Types'Unchecked_Access; procedure Prepare_Table (Table : in Table_Definition_Access) is C : Column_List.Cursor := Table.Members.First; begin Table.Prepare; -- Walk the columns to get their type. while Column_List.Has_Element (C) loop declare Col : constant Column_Definition_Access := Column_List.Element (C); T : constant String := To_String (Col.Type_Name); Name : constant String := Gen.Utils.Get_Package_Name (T); begin if not Col.Is_Basic_Type and Name'Length > 0 and Name /= O.Pkg_Name then Used_Types.Include (To_Unbounded_String (Name)); elsif T = "Time" or T = "Date" or T = "Timestamp" or T = "Nullable_Time" then O.Uses_Calendar_Time := True; end if; end; Column_List.Next (C); end loop; end Prepare_Table; procedure Prepare_Tables (Tables : in Table_List.List_Definition) is Table_Iter : Table_List.Cursor := Tables.First; begin while Table_List.Has_Element (Table_Iter) loop declare Table : constant Definition_Access := Table_List.Element (Table_Iter); begin if Table.all in Table_Definition'Class then Prepare_Table (Table_Definition_Access (Table)); else Table.Prepare; end if; end; Table_List.Next (Table_Iter); end loop; end Prepare_Tables; begin Log.Info ("Preparing package {0}", O.Pkg_Name); O.Used := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Used_Types.Row := 0; O.Used_Types.Values.Clear; O.Uses_Calendar_Time := False; O.Enums.Sort; O.Queries.Sort; Prepare_Tables (O.Enums); Prepare_Tables (O.Tables); Prepare_Tables (O.Queries); declare P : Gen.Utils.String_Set.Cursor := Used_Types.First; begin while Gen.Utils.String_Set.Has_Element (P) loop declare Name : constant Unbounded_String := Gen.Utils.String_Set.Element (P); begin Log.Info ("with {0}", Name); O.Used_Types.Values.Append (Util.Beans.Objects.To_Object (Name)); end; Gen.Utils.String_Set.Next (P); end loop; end; end Prepare; -- ------------------------------ -- Initialize the package instance -- ------------------------------ overriding procedure Initialize (O : in out Package_Definition) is use Util.Beans.Objects; begin O.Enums_Bean := Util.Beans.Objects.To_Object (O.Enums'Unchecked_Access, STATIC); O.Tables_Bean := Util.Beans.Objects.To_Object (O.Tables'Unchecked_Access, STATIC); O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access, STATIC); O.Beans_Bean := Util.Beans.Objects.To_Object (O.Beans'Unchecked_Access, STATIC); O.Used := Util.Beans.Objects.To_Object (O.Used_Types'Unchecked_Access, STATIC); end Initialize; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : List_Object) return Natural is begin Log.Debug ("Length {0}", Natural'Image (Natural (From.Values.Length))); return Natural (From.Values.Length); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural) is begin Log.Debug ("Setting row {0}", Natural'Image (Index)); From.Row := Index; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : List_Object) return Util.Beans.Objects.Object is begin Log.Debug ("Getting row {0}", Natural'Image (From.Row)); return From.Values.Element (From.Row - 1); end Get_Row; -- ------------------------------ -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); pragma Unreferenced (Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- 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 Model_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tables" then return From.Tables_Bean; elsif Name = "dirname" then return Util.Beans.Objects.To_Object (From.Dir_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. -- ------------------------------ procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String) is begin O.Dir_Name := To_Unbounded_String (Target_Dir); O.DB_Name := To_Unbounded_String (Model_Dir); end Set_Dirname; -- ------------------------------ -- Get the directory name associated with the model. -- ------------------------------ function Get_Dirname (O : in Model_Definition) return String is begin return To_String (O.Dir_Name); end Get_Dirname; -- ------------------------------ -- Get the directory name which contains the model. -- ------------------------------ function Get_Model_Directory (O : in Model_Definition) return String is begin return To_String (O.DB_Name); end Get_Model_Directory; -- ------------------------------ -- Initialize the model definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Model_Definition) is T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Tables'Unchecked_Access; begin O.Tables_Bean := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Dir_Name := To_Unbounded_String ("src"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Model_Definition) is Iter : Package_Cursor := O.Packages.First; begin while Has_Element (Iter) loop Element (Iter).Prepare; Next (Iter); end loop; O.Tables.Sort; end Prepare; -- ------------------------------ -- Get the first package of the model definition. -- ------------------------------ function First (From : Model_Definition) return Package_Cursor is begin return From.Packages.First; end First; -- ------------------------------ -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. -- ------------------------------ procedure Register_Type (O : in out Model_Definition; From : in String; To : in String) is begin null; end Register_Type; end Gen.Model.Packages;
Initialize the beans object to give access to the list of model Ada beans to generate
Initialize the beans object to give access to the list of model Ada beans to generate
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
7dc800428fd5797ba882e301f7f84e2d5e9578f7
src/asf-principals.ads
src/asf-principals.ads
----------------------------------------------------------------------- -- asf-principals -- Component and tag factory -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; package ASF.Principals is -- ------------------------------ -- Principal -- ------------------------------ subtype Principal is Security.Permissions.Principal; subtype Principal_Access is Security.Permissions.Principal_Access; end ASF.Principals;
----------------------------------------------------------------------- -- asf-principals -- Component and tag factory -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security; package ASF.Principals is -- ------------------------------ -- Principal -- ------------------------------ subtype Principal is Security.Principal; subtype Principal_Access is Security.Principal_Access; end ASF.Principals;
Update to use Security.Principal
Update to use Security.Principal
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
dbaf81023f35335d1dbc916bd0f1566c132d76e4
src/core/concurrent/util-concurrent-fifos.adb
src/core/concurrent/util-concurrent-fifos.adb
----------------------------------------------------------------------- -- util-concurrent-fifos -- Concurrent Fifo Queues -- Copyright (C) 2012, 2014, 2015, 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; package body Util.Concurrent.Fifos is -- ------------------------------ -- Put the element in the queue. -- ------------------------------ procedure Enqueue (Into : in out Fifo; Item : in Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then Into.Buffer.Enqueue (Item); else select Into.Buffer.Enqueue (Item); or delay Wait; raise Timeout; end select; end if; end Enqueue; -- ------------------------------ -- Get an element from the queue. -- Wait until one element gets available. -- ------------------------------ procedure Dequeue (From : in out Fifo; Item : out Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then From.Buffer.Dequeue (Item); else select From.Buffer.Dequeue (Item); or delay Wait; raise Timeout; end select; end if; end Dequeue; -- ------------------------------ -- Wait for the fifo to become empty. -- ------------------------------ procedure Wait_Empty (From : in out Fifo) is begin From.Buffer.Wait_Empty; end Wait_Empty; -- ------------------------------ -- Get the number of elements in the queue. -- ------------------------------ function Get_Count (From : in Fifo) return Natural is begin return From.Buffer.Get_Count; end Get_Count; -- ------------------------------ -- Set the queue size. -- ------------------------------ procedure Set_Size (Into : in out Fifo; Capacity : in Positive) is begin Into.Buffer.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Initializes the queue. -- ------------------------------ overriding procedure Initialize (Object : in out Fifo) is begin Object.Buffer.Set_Size (Default_Size); end Initialize; -- ------------------------------ -- Release the queue elements. -- ------------------------------ overriding procedure Finalize (Object : in out Fifo) is begin if Clear_On_Dequeue then while Object.Get_Count > 0 loop declare Unused : Element_Type; begin Object.Dequeue (Unused); end; end loop; end if; Object.Buffer.Set_Size (0); end Finalize; -- Queue of objects. protected body Protected_Fifo is -- ------------------------------ -- Put the element in the queue. -- If the queue is full, wait until some room is available. -- ------------------------------ entry Enqueue (Item : in Element_Type) when Count < Elements'Length - (if Clear_On_Dequeue then 1 else 0) is begin Elements (Last) := Item; Last := Last + 1; if Last > Elements'Last then if Clear_On_Dequeue then Last := Elements'First + 1; else Last := Elements'First; end if; end if; Count := Count + 1; end Enqueue; -- ------------------------------ -- Get an element from the queue. -- Wait until one element gets available. -- ------------------------------ entry Dequeue (Item : out Element_Type) when Count > 0 is begin Count := Count - 1; Item := Elements (First); -- For the clear on dequeue mode, erase the queue element. -- If the element holds some storage or a reference, this gets cleared here. -- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue -- is false). There is no overhead when this is not used -- (ie, instantiation/compile time flag). if Clear_On_Dequeue then Elements (First) := Elements (0); end if; First := First + 1; if First > Elements'Last then if Clear_On_Dequeue then First := Elements'First + 1; else First := Elements'First; end if; end if; end Dequeue; -- ------------------------------ -- Wait for the queue to become empty. -- ------------------------------ entry Wait_Empty when Count = 0 is begin null; end Wait_Empty; -- ------------------------------ -- Get the number of elements in the queue. -- ------------------------------ function Get_Count return Natural is begin return Count; end Get_Count; -- ------------------------------ -- Set the queue size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); First_Pos : Natural := 1; begin if Clear_On_Dequeue then First_Pos := 0; end if; if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (First_Pos .. Capacity); else declare New_Array : constant Element_Array_Access := new Element_Array (First_Pos .. Capacity); begin if Capacity > Elements'Length then New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last); else New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; end Protected_Fifo; end Util.Concurrent.Fifos;
----------------------------------------------------------------------- -- util-concurrent-fifos -- Concurrent Fifo Queues -- Copyright (C) 2012, 2014, 2015, 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; package body Util.Concurrent.Fifos is -- ------------------------------ -- Put the element in the queue. -- ------------------------------ procedure Enqueue (Into : in out Fifo; Item : in Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then Into.Buffer.Enqueue (Item); else select Into.Buffer.Enqueue (Item); or delay Wait; raise Timeout; end select; end if; end Enqueue; -- ------------------------------ -- Get an element from the queue. -- Wait until one element gets available. -- ------------------------------ procedure Dequeue (From : in out Fifo; Item : out Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then From.Buffer.Dequeue (Item); else select From.Buffer.Dequeue (Item); or delay Wait; raise Timeout; end select; end if; end Dequeue; -- ------------------------------ -- Wait for the fifo to become empty. -- ------------------------------ procedure Wait_Empty (From : in out Fifo) is begin From.Buffer.Wait_Empty; end Wait_Empty; -- ------------------------------ -- Get the number of elements in the queue. -- ------------------------------ function Get_Count (From : in Fifo) return Natural is begin return From.Buffer.Get_Count; end Get_Count; -- ------------------------------ -- Set the queue size. -- ------------------------------ procedure Set_Size (Into : in out Fifo; Capacity : in Positive) is begin Into.Buffer.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Initializes the queue. -- ------------------------------ overriding procedure Initialize (Object : in out Fifo) is begin Object.Buffer.Set_Size (Default_Size); end Initialize; -- ------------------------------ -- Release the queue elements. -- ------------------------------ overriding procedure Finalize (Object : in out Fifo) is begin if Clear_On_Dequeue then while Object.Get_Count > 0 loop declare Unused : Element_Type; begin Object.Dequeue (Unused); end; end loop; end if; Object.Buffer.Set_Size (0); end Finalize; -- Queue of objects. protected body Protected_Fifo is -- ------------------------------ -- Put the element in the queue. -- If the queue is full, wait until some room is available. -- ------------------------------ entry Enqueue (Item : in Element_Type) when Count < Elements'Length - (if Clear_On_Dequeue then 1 else 0) is begin Elements (Last) := Item; Last := Last + 1; if Last > Elements'Last then if Clear_On_Dequeue then Last := Elements'First + 1; else Last := Elements'First; end if; end if; Count := Count + 1; end Enqueue; -- ------------------------------ -- Get an element from the queue. -- Wait until one element gets available. -- ------------------------------ entry Dequeue (Item : out Element_Type) when Count > 0 is begin Count := Count - 1; Item := Elements (First); -- For the clear on dequeue mode, erase the queue element. -- If the element holds some storage or a reference, this gets cleared here. -- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue -- is false). There is no overhead when this is not used -- (ie, instantiation/compile time flag). if Clear_On_Dequeue then Elements (First) := Elements (0); end if; First := First + 1; if First > Elements'Last then if Clear_On_Dequeue then First := Elements'First + 1; else First := Elements'First; end if; end if; end Dequeue; -- ------------------------------ -- Wait for the queue to become empty. -- ------------------------------ entry Wait_Empty when Count = 0 is begin null; end Wait_Empty; -- ------------------------------ -- Get the number of elements in the queue. -- ------------------------------ function Get_Count return Natural is begin return Count; end Get_Count; -- ------------------------------ -- Set the queue size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); First_Pos : Natural := 1; begin if Clear_On_Dequeue then First_Pos := 0; end if; if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (First_Pos .. Capacity); else declare New_Array : constant Element_Array_Access := new Element_Array (First_Pos .. Capacity); begin if Capacity > Elements'Length then New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last); else New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; end Protected_Fifo; end Util.Concurrent.Fifos;
Fix style warning
Fix style warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e4be8c3309cd62fdb13d223d013b5ce9cabe5900
src/sys/encoders/util-encoders-quoted_printable.adb
src/sys/encoders/util-encoders-quoted_printable.adb
----------------------------------------------------------------------- -- util-encoders-quoted_printable -- Encode/Decode a stream in quoted-printable -- 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.Characters.Handling; with Interfaces; package body Util.Encoders.Quoted_Printable is use Ada.Characters.Handling; use type Interfaces.Unsigned_8; function From_Hex (C : in Character) return Interfaces.Unsigned_8 is (if C >= '0' and C <= '9' then Character'Pos (C) - Character'Pos ('0') elsif C >= 'A' and C <= 'F' then Character'Pos (C) - Character'Pos ('A') + 10 else 0); function From_Hex (C1, C2 : in Character) return Character is (Character'Val (From_Hex (C2) + Interfaces.Shift_Left (From_Hex (C1), 4))); -- ------------------------------ -- Decode the Quoted-Printable string and return the result. -- When Strict is true, raises the Encoding_Error exception if the -- format is invalid. Otherwise, ignore invalid encoding. -- ------------------------------ function Decode (Content : in String; Strict : in Boolean := True) return String is Result : String (1 .. Content'Length); Read_Pos : Natural := Content'First; Write_Pos : Natural := Result'First - 1; C : Character; C2 : Character; begin while Read_Pos <= Content'Last loop C := Content (Read_Pos); if C = '=' then exit when Read_Pos = Content'Last; if Read_Pos + 2 > Content'Last then exit when not Strict; raise Encoding_Error; end if; Read_Pos := Read_Pos + 1; C := Content (Read_Pos); if not Is_Hexadecimal_Digit (C) then exit when not Strict; raise Encoding_Error; end if; C2 := Content (Read_Pos + 1); if not Is_Hexadecimal_Digit (C) then exit when not Strict; raise Encoding_Error; end if; Write_Pos := Write_Pos + 1; Result (Write_Pos) := From_Hex (C, C2); Read_Pos := Read_Pos + 1; else Write_Pos := Write_Pos + 1; Result (Write_Pos) := C; end if; Read_Pos := Read_Pos + 1; end loop; return Result (1 .. Write_Pos); end Decode; -- ------------------------------ -- Decode the "Q" encoding, similar to Quoted-Printable but with -- spaces that can be replaced by '_'. -- See RFC 2047. -- ------------------------------ function Q_Decode (Content : in String; Strict : in Boolean := True) return String is Result : String (1 .. Content'Length); Read_Pos : Natural := Content'First; Write_Pos : Natural := Result'First - 1; C : Character; C2 : Character; begin while Read_Pos <= Content'Last loop C := Content (Read_Pos); if C = '=' then exit when Read_Pos = Content'Last; if Read_Pos + 2 > Content'Last then exit when not Strict; raise Encoding_Error; end if; Read_Pos := Read_Pos + 1; C := Content (Read_Pos); if not Is_Hexadecimal_Digit (C) then exit when not Strict; raise Encoding_Error; end if; C2 := Content (Read_Pos + 1); if not Is_Hexadecimal_Digit (C) then exit when not Strict; raise Encoding_Error; end if; Write_Pos := Write_Pos + 1; Result (Write_Pos) := From_Hex (C, C2); Read_Pos := Read_Pos + 1; elsif C = '_' then Write_Pos := Write_Pos + 1; Result (Write_Pos) := C; else Write_Pos := Write_Pos + 1; Result (Write_Pos) := C; end if; Read_Pos := Read_Pos + 1; end loop; return Result (1 .. Write_Pos); end Q_Decode; end Util.Encoders.Quoted_Printable;
----------------------------------------------------------------------- -- util-encoders-quoted_printable -- Encode/Decode a stream in quoted-printable -- 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.Characters.Handling; with Interfaces; package body Util.Encoders.Quoted_Printable is use Ada.Characters.Handling; use type Interfaces.Unsigned_8; function From_Hex (C : in Character) return Interfaces.Unsigned_8 is (if C >= '0' and C <= '9' then Character'Pos (C) - Character'Pos ('0') elsif C >= 'A' and C <= 'F' then Character'Pos (C) - Character'Pos ('A') + 10 else 0); function From_Hex (C1, C2 : in Character) return Character is (Character'Val (From_Hex (C2) + Interfaces.Shift_Left (From_Hex (C1), 4))); -- ------------------------------ -- Decode the Quoted-Printable string and return the result. -- When Strict is true, raises the Encoding_Error exception if the -- format is invalid. Otherwise, ignore invalid encoding. -- ------------------------------ function Decode (Content : in String; Strict : in Boolean := True) return String is Result : String (1 .. Content'Length); Read_Pos : Natural := Content'First; Write_Pos : Natural := Result'First - 1; C : Character; C2 : Character; begin while Read_Pos <= Content'Last loop C := Content (Read_Pos); if C = '=' then exit when Read_Pos = Content'Last; if Read_Pos + 2 > Content'Last then exit when not Strict; raise Encoding_Error; end if; Read_Pos := Read_Pos + 1; C := Content (Read_Pos); if not Is_Hexadecimal_Digit (C) then exit when not Strict; raise Encoding_Error; end if; C2 := Content (Read_Pos + 1); if not Is_Hexadecimal_Digit (C) then exit when not Strict; raise Encoding_Error; end if; Write_Pos := Write_Pos + 1; Result (Write_Pos) := From_Hex (C, C2); Read_Pos := Read_Pos + 1; else Write_Pos := Write_Pos + 1; Result (Write_Pos) := C; end if; Read_Pos := Read_Pos + 1; end loop; return Result (1 .. Write_Pos); end Decode; -- ------------------------------ -- Decode the "Q" encoding, similar to Quoted-Printable but with -- spaces that can be replaced by '_'. -- See RFC 2047. -- ------------------------------ function Q_Decode (Content : in String) return String is Result : String (1 .. Content'Length); Read_Pos : Natural := Content'First; Write_Pos : Natural := Result'First - 1; C : Character; C2 : Character; begin while Read_Pos <= Content'Last loop C := Content (Read_Pos); if C = '=' then exit when Read_Pos = Content'Last or else Read_Pos + 2 > Content'Last; Read_Pos := Read_Pos + 1; C := Content (Read_Pos); exit when not Is_Hexadecimal_Digit (C); C2 := Content (Read_Pos + 1); exit when not Is_Hexadecimal_Digit (C); Write_Pos := Write_Pos + 1; Result (Write_Pos) := From_Hex (C, C2); Read_Pos := Read_Pos + 1; elsif C = '_' then Write_Pos := Write_Pos + 1; Result (Write_Pos) := ' '; else Write_Pos := Write_Pos + 1; Result (Write_Pos) := C; end if; Read_Pos := Read_Pos + 1; end loop; return Result (1 .. Write_Pos); end Q_Decode; end Util.Encoders.Quoted_Printable;
Implement Q_Decode operation
Implement Q_Decode operation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5a215caa4f8d122c8fccff9ccb9f6ea0fc8b0282
src/sys/http/util-http-clients.ads
src/sys/http/util-http-clients.ads
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- 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 Ada.Finalization; with Util.Streams.Texts; with Util.Serialize.IO.Form; with Util.Http.Cookies; -- == Client == -- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send -- requests to an HTTP server. -- -- === GET request === -- To retrieve a content using the HTTP GET operation, a client instance must be created. -- The response is returned in a specific object that must therefore be declared: -- -- Http : Util.Http.Clients.Client; -- Response : Util.Http.Clients.Response; -- -- Before invoking the GET operation, the client can setup a number of HTTP headers. -- -- Http.Add_Header ("X-Requested-By", "wget"); -- -- The GET operation is performed when the <tt>Get</tt> procedure is called: -- -- Http.Get ("http://www.google.com", Response); -- -- Once the response is received, the <tt>Response</tt> object contains the status of the -- HTTP response, the HTTP reply headers and the body. A response header can be obtained -- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>: -- -- Body : constant String := Response.Get_Body; -- package Util.Http.Clients is Connection_Error : exception; type Form_Data is limited new Util.Serialize.IO.Form.Output_Stream with private; procedure Initialize (Form : in out Form_Data; Size : in Positive); -- ------------------------------ -- Http response -- ------------------------------ -- The <b>Response</b> type represents a response returned by an HTTP request. type Response is limited new Abstract_Response with private; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean; -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Reply : in Response; Name : in String) return String; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String); -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String); -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)); -- Get the response body as a string. overriding function Get_Body (Reply : in Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Response) return Natural; -- ------------------------------ -- Http client -- ------------------------------ -- The <b>Client</b> type allows to execute HTTP GET/POST requests. type Client is limited new Abstract_Request with private; type Client_Access is access all Client; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Request : in Client; Name : in String) return Boolean; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in Client; Name : in String) return String; -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String); -- Adds a header with the given name and value. -- This method allows headers to have multiple values. overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String); -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)); -- Removes all headers with the given name. procedure Remove_Header (Request : in out Client; Name : in String); -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie); -- Set the timeout for the connection. procedure Set_Timeout (Request : in out Client; Timeout : in Duration); -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class); -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); procedure Post (Request : in out Client; URL : in String; Data : in Form_Data'Class; Reply : out Response'Class); -- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. procedure Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); -- Execute a http DELETE request on the given URL. procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class); private subtype Http_Request is Abstract_Request; subtype Http_Request_Access is Abstract_Request_Access; subtype Http_Response is Abstract_Response; subtype Http_Response_Access is Abstract_Response_Access; type Http_Manager is interface; type Http_Manager_Access is access all Http_Manager'Class; procedure Create (Manager : in Http_Manager; Http : in out Client'Class) is abstract; procedure Do_Get (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Post (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Put (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Delete (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; -- Set the timeout for the connection. procedure Set_Timeout (Manager : in Http_Manager; Http : in Client'Class; Timeout : in Duration) is abstract; Default_Http_Manager : Http_Manager_Access; type Response is limited new Ada.Finalization.Limited_Controlled and Abstract_Response with record Delegate : Abstract_Response_Access; end record; -- Free the resource used by the response. overriding procedure Finalize (Reply : in out Response); type Client is limited new Ada.Finalization.Limited_Controlled and Abstract_Request with record Manager : Http_Manager_Access; Delegate : Http_Request_Access; end record; -- Initialize the client overriding procedure Initialize (Http : in out Client); overriding procedure Finalize (Http : in out Client); type Form_Data is limited new Util.Serialize.IO.Form.Output_Stream with record Buffer : aliased Util.Streams.Texts.Print_Stream; end record; end Util.Http.Clients;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2015, 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.Finalization; with Util.Streams.Texts; with Util.Serialize.IO.Form; with Util.Http.Cookies; -- == Client == -- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send -- requests to an HTTP server. -- -- === GET request === -- To retrieve a content using the HTTP GET operation, a client instance must be created. -- The response is returned in a specific object that must therefore be declared: -- -- Http : Util.Http.Clients.Client; -- Response : Util.Http.Clients.Response; -- -- Before invoking the GET operation, the client can setup a number of HTTP headers. -- -- Http.Add_Header ("X-Requested-By", "wget"); -- -- The GET operation is performed when the <tt>Get</tt> procedure is called: -- -- Http.Get ("http://www.google.com", Response); -- -- Once the response is received, the <tt>Response</tt> object contains the status of the -- HTTP response, the HTTP reply headers and the body. A response header can be obtained -- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>: -- -- Body : constant String := Response.Get_Body; -- package Util.Http.Clients is Connection_Error : exception; type Form_Data is limited new Util.Serialize.IO.Form.Output_Stream with private; procedure Initialize (Form : in out Form_Data; Size : in Positive); -- ------------------------------ -- Http response -- ------------------------------ -- The <b>Response</b> type represents a response returned by an HTTP request. type Response is limited new Abstract_Response with private; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean; -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Reply : in Response; Name : in String) return String; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String); -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String); -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)); -- Get the response body as a string. overriding function Get_Body (Reply : in Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Response) return Natural; -- ------------------------------ -- Http client -- ------------------------------ -- The <b>Client</b> type allows to execute HTTP GET/POST requests. type Client is limited new Abstract_Request with private; type Client_Access is access all Client; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Request : in Client; Name : in String) return Boolean; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in Client; Name : in String) return String; -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String); -- Adds a header with the given name and value. -- This method allows headers to have multiple values. overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String); -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)); -- Removes all headers with the given name. procedure Remove_Header (Request : in out Client; Name : in String); -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie); -- Set the timeout for the connection. procedure Set_Timeout (Request : in out Client; Timeout : in Duration); -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class); -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); procedure Post (Request : in out Client; URL : in String; Data : in Form_Data'Class; Reply : out Response'Class); -- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. procedure Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); -- Execute an http PATCH request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. procedure Patch (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); -- Execute a http DELETE request on the given URL. procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class); -- Execute an http HEAD request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. procedure Head (Request : in out Client; URL : in String; Reply : out Response'Class); -- Execute an http OPTIONS request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. procedure Options (Request : in out Client; URL : in String; Reply : out Response'Class); private subtype Http_Request is Abstract_Request; subtype Http_Request_Access is Abstract_Request_Access; subtype Http_Response is Abstract_Response; subtype Http_Response_Access is Abstract_Response_Access; type Http_Manager is interface; type Http_Manager_Access is access all Http_Manager'Class; procedure Create (Manager : in Http_Manager; Http : in out Client'Class) is abstract; procedure Do_Get (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Head (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Post (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Put (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Patch (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; procedure Do_Delete (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Options (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; -- Set the timeout for the connection. procedure Set_Timeout (Manager : in Http_Manager; Http : in Client'Class; Timeout : in Duration) is abstract; Default_Http_Manager : Http_Manager_Access; type Response is limited new Ada.Finalization.Limited_Controlled and Abstract_Response with record Delegate : Abstract_Response_Access; end record; -- Free the resource used by the response. overriding procedure Finalize (Reply : in out Response); type Client is limited new Ada.Finalization.Limited_Controlled and Abstract_Request with record Manager : Http_Manager_Access; Delegate : Http_Request_Access; end record; -- Initialize the client overriding procedure Initialize (Http : in out Client); overriding procedure Finalize (Http : in out Client); type Form_Data is limited new Util.Serialize.IO.Form.Output_Stream with record Buffer : aliased Util.Streams.Texts.Print_Stream; end record; end Util.Http.Clients;
Add support for the HTTP Head, Patch and Options
Add support for the HTTP Head, Patch and Options
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
81cae2d58d7cf467180d8bb53ef06a83123a7bbd
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Wiki.Utils; with Wiki.Parsers; -- This example reads an XHTML file and renders the result. -- render -html -dotclear -markdown infile -- render -text procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; Count : Natural := 0; Html_Mode : Boolean := True; Syntax : Wiki.Parsers.Wiki_Syntax_Type := Wiki.Parsers.SYNTAX_MARKDOWN; begin loop case Getopt ("t f:") is when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin Ada.Text_IO.Put_Line (Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Ada.Text_IO.Put_Line ("Usage: render [-DNAME=VALUE ] file"); Ada.Text_IO.Put_Line ("Example: render -DcontextPath=/test samples/web/ajax.xhtml"); end if; return; end if; Count := Count + 1; Util.Files.Read_File (Name, Data); if Html_Mode then Ada.Text_IO.Put_Line (Wiki.Utils.To_Html (To_Wide_Wide_String (To_String (Data)), Syntax)); else Ada.Text_IO.Put_Line (Wiki.Utils.To_Text (To_Wide_Wide_String (To_String (Data)), Syntax)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; end Render;
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with Ada.Characters.Conversions; with GNAT.Command_Line; with Util.Files; with Wiki.Utils; with Wiki.Parsers; -- This example reads an XHTML file and renders the result. -- render -html -dotclear -markdown infile -- render -text procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use Ada.Strings.Unbounded; use Ada.Characters.Conversions; Count : Natural := 0; Html_Mode : Boolean := True; Syntax : Wiki.Parsers.Wiki_Syntax_Type := Wiki.Parsers.SYNTAX_MARKDOWN; begin loop case Getopt ("m M d c t f:") is when 'm' => Syntax := Wiki.Parsers.SYNTAX_MARKDOWN; when 'M' => Syntax := Wiki.Parsers.SYNTAX_MEDIA_WIKI; when 'c' => Syntax := Wiki.Parsers.SYNTAX_CREOLE; when 'd' => Syntax := Wiki.Parsers.SYNTAX_DOTCLEAR; when 't' => Html_Mode := False; when 'f' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin Ada.Text_IO.Put_Line (Value); end; when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Data : Unbounded_String; begin if Name = "" then if Count = 0 then Ada.Text_IO.Put_Line ("Usage: render [-DNAME=VALUE ] file"); Ada.Text_IO.Put_Line ("Example: render -DcontextPath=/test samples/web/ajax.xhtml"); end if; return; end if; Count := Count + 1; Util.Files.Read_File (Name, Data); if Html_Mode then Ada.Text_IO.Put_Line (Wiki.Utils.To_Html (To_Wide_Wide_String (To_String (Data)), Syntax)); else Ada.Text_IO.Put_Line (Wiki.Utils.To_Text (To_Wide_Wide_String (To_String (Data)), Syntax)); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; end Render;
Add several options to render using different Wiki syntax
Add several options to render using different Wiki syntax
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
dbce245b2689f42fbd32fa58fab3a6f1e5bb9ad7
samples/userdb.adb
samples/userdb.adb
----------------------------------------------------------------------- -- userdb -- Example to find/create an object from the database -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with ADO.Drivers; with ADO.Sessions; with ADO.SQL; with ADO.Sessions.Factory; with Samples.User.Model; with Ada.Text_IO; with Ada.Strings.Unbounded; with ADO.Statements; with ADO.Queries; with Util.Log.Loggers; with GNAT.Command_Line; procedure Userdb is use ADO; use Ada; use Ada.Strings.Unbounded; use Samples.User.Model; use ADO.Statements; use GNAT.Command_Line; Factory : ADO.Sessions.Factory.Session_Factory; User : User_Ref; Users : User_Vector; procedure List_Users (Filter : in String); procedure List_User_Info; procedure Initialize (File : in String); -- ------------------------------ -- List users -- ------------------------------ procedure List_Users (Filter : in String) is use User_Vectors; DB : ADO.Sessions.Session := Factory.Get_Session; Statement : ADO.Statements.Query_Statement := DB.Create_Statement (Filter); Query : ADO.SQL.Query; begin List (Object => Users, Session => DB, Query => Query); if Users.Is_Empty then Text_IO.Put_Line ("List is empty"); else declare Iter : User_Vectors.Cursor := First (Users); begin while Has_Element (Iter) loop User := Element (Iter); Text_IO.Put_Line (Identifier'Image (User.Get_Id) & " " & To_String (User.Get_Name) & " " & To_String (User.Get_Email)); User_Vectors.Next (Iter); end loop; end; end if; Statement := DB.Create_Statement ("select count(*) from user"); Statement.Execute; if not Statement.Has_Elements then Text_IO.Put_Line ("Count query failed..."); end if; declare Count : constant Integer := Statement.Get_Integer (0); begin Text_IO.Put_Line ("Count: " & Integer'Image (Count)); end; end List_Users; -- ------------------------------ -- List users -- ------------------------------ procedure List_User_Info is use Samples.User.Model.User_Info_Vectors; DB : ADO.Sessions.Session := Factory.Get_Session; Users : Samples.User.Model.User_Info_Vector; Context : ADO.Queries.Context; begin Context.Set_Query (Samples.User.Model.Query_User_List); List (Object => Users, Session => DB, Context => Context); if Users.Is_Empty then Text_IO.Put_Line ("User info list is empty"); else declare Iter : Cursor := First (Users); User : Samples.User.Model.User_Info; begin while Has_Element (Iter) loop User := Element (Iter); Text_IO.Put_Line (Identifier'Image (User.Id) & " " & To_String (User.Name) & " " & To_String (User.Email)); Next (Iter); end loop; end; end if; end List_User_Info; procedure Initialize (File : in String) is begin Util.Log.Loggers.Initialize (File); ADO.Drivers.Initialize (File); end Initialize; begin Initialize ("samples.properties"); Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; Query : ADO.SQL.Query; Found : Boolean; begin DB.Begin_Transaction; List_User_Info; List_Users (Filter => ""); loop declare Name : constant String := Get_Argument; begin exit when Name = ""; Query.Bind_Param (1, Name); Query.Set_Filter ("name = ?"); User.Find (Session => DB, Query => Query, Found => Found); if User.Is_Null or not Found then User.Set_Name (Name); User.Set_Email (Name & "@gmail.com"); User.Set_Description ("My friend " & Name); -- User.Set_Password ("my password"); User.Set_Status (0); User.Save (DB); Text_IO.Put_Line ("User created: " & Identifier'Image (User.Get_Id)); else Text_IO.Put_Line ("User " & Name & ": " & Identifier'Image (User.Get_Id)); end if; end; end loop; DB.Rollback; exception when ADO.Sessions.NOT_FOUND => Text_IO.Put_Line ("User 23 does not exist"); end; Text_IO.Put_Line ("Exiting"); end Userdb;
----------------------------------------------------------------------- -- userdb -- Example to find/create an object from the database -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with ADO.Drivers.Initializer; with ADO.Sessions; with ADO.SQL; with ADO.Sessions.Factory; with Samples.User.Model; with Ada.Text_IO; with Ada.Strings.Unbounded; with ADO.Statements; with ADO.Queries; with Util.Log.Loggers; with GNAT.Command_Line; procedure Userdb is use ADO; use Ada; use Ada.Strings.Unbounded; use Samples.User.Model; use ADO.Statements; use GNAT.Command_Line; Factory : ADO.Sessions.Factory.Session_Factory; User : User_Ref; Users : User_Vector; procedure List_Users (Filter : in String); procedure List_User_Info; procedure Initialize (File : in String); -- ------------------------------ -- List users -- ------------------------------ procedure List_Users (Filter : in String) is use User_Vectors; DB : ADO.Sessions.Session := Factory.Get_Session; Statement : ADO.Statements.Query_Statement := DB.Create_Statement (Filter); Query : ADO.SQL.Query; begin List (Object => Users, Session => DB, Query => Query); if Users.Is_Empty then Text_IO.Put_Line ("List is empty"); else declare Iter : User_Vectors.Cursor := First (Users); begin while Has_Element (Iter) loop User := Element (Iter); Text_IO.Put_Line (Identifier'Image (User.Get_Id) & " " & To_String (User.Get_Name) & " " & To_String (User.Get_Email)); User_Vectors.Next (Iter); end loop; end; end if; Statement := DB.Create_Statement ("select count(*) from user"); Statement.Execute; if not Statement.Has_Elements then Text_IO.Put_Line ("Count query failed..."); end if; declare Count : constant Integer := Statement.Get_Integer (0); begin Text_IO.Put_Line ("Count: " & Integer'Image (Count)); end; end List_Users; -- ------------------------------ -- List users -- ------------------------------ procedure List_User_Info is use Samples.User.Model.User_Info_Vectors; DB : ADO.Sessions.Session := Factory.Get_Session; Users : Samples.User.Model.User_Info_Vector; Context : ADO.Queries.Context; begin Context.Set_Query (Samples.User.Model.Query_User_List); List (Object => Users, Session => DB, Context => Context); if Users.Is_Empty then Text_IO.Put_Line ("User info list is empty"); else declare Iter : Cursor := First (Users); User : Samples.User.Model.User_Info; begin while Has_Element (Iter) loop User := Element (Iter); Text_IO.Put_Line (Identifier'Image (User.Id) & " " & To_String (User.Name) & " " & To_String (User.Email)); Next (Iter); end loop; end; end if; end List_User_Info; procedure Initialize (File : in String) is procedure Init is new ADO.Drivers.Initializer (String, ADO.Drivers.Initialize); begin Util.Log.Loggers.Initialize (File); Init (File); end Initialize; begin Initialize ("samples.properties"); Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; Query : ADO.SQL.Query; Found : Boolean; begin DB.Begin_Transaction; List_User_Info; List_Users (Filter => ""); loop declare Name : constant String := Get_Argument; begin exit when Name = ""; Query.Bind_Param (1, Name); Query.Set_Filter ("name = ?"); User.Find (Session => DB, Query => Query, Found => Found); if User.Is_Null or not Found then User.Set_Name (Name); User.Set_Email (Name & "@gmail.com"); User.Set_Description ("My friend " & Name); -- User.Set_Password ("my password"); User.Set_Status (0); User.Save (DB); Text_IO.Put_Line ("User created: " & Identifier'Image (User.Get_Id)); else Text_IO.Put_Line ("User " & Name & ": " & Identifier'Image (User.Get_Id)); end if; end; end loop; DB.Rollback; exception when ADO.Sessions.NOT_FOUND => Text_IO.Put_Line ("User 23 does not exist"); end; Text_IO.Put_Line ("Exiting"); end Userdb;
Update the driver initialization
Update the driver initialization
Ada
apache-2.0
Letractively/ada-ado
9bed8a889ebe8568014dc9738a1a54c1f8bb37dc
src/asf-beans-mappers.adb
src/asf-beans-mappers.adb
----------------------------------------------------------------------- -- asf-beans-mappers -- Read XML managed bean declaratiosn -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ASF.Beans.Mappers is Empty : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (String '("")); Empty_Params : ASF.Beans.Parameter_Bean_Ref.Ref; -- ------------------------------ -- Set the field identified by <b>Field</b> with the <b>Value</b>. -- ------------------------------ procedure Set_Member (MBean : in out Managed_Bean; Field : in Managed_Bean_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => MBean.Name := Value; when FIELD_CLASS => MBean.Class := Value; when FIELD_SCOPE => declare Scope : constant String := Util.Beans.Objects.To_String (Value); begin if Scope = "request" then MBean.Scope := REQUEST_SCOPE; elsif Scope = "session" then MBean.Scope := SESSION_SCOPE; elsif Scope = "application" then MBean.Scope := APPLICATION_SCOPE; else raise Util.Serialize.Mappers.Field_Error with "Invalid scope: " & Scope; end if; end; when FIELD_PROPERTY_NAME => MBean.Prop_Name := Value; when FIELD_PROPERTY_VALUE => MBean.Prop_Value := Value; when FIELD_PROPERTY_CLASS => null; when FIELD_PROPERTY => -- Create the parameter list only the first time a property is seen. if MBean.Params.Is_Null then MBean.Params := ASF.Beans.Parameter_Bean_Ref.Create (new ASF.Beans.Parameter_Bean); end if; -- Add the parameter. The property value is parsed as an EL expression. EL.Beans.Add_Parameter (MBean.Params.Value.all.Params, Util.Beans.Objects.To_String (MBean.Prop_Name), Util.Beans.Objects.To_String (MBean.Prop_Value), MBean.Context.all); MBean.Prop_Name := Empty; MBean.Prop_Value := Empty; when FIELD_MANAGED_BEAN => declare Name : constant String := Util.Beans.Objects.To_String (MBean.Name); Class : constant String := Util.Beans.Objects.To_String (MBean.Class); begin Register (Factory => MBean.Factory.all, Name => Name, Class => Class, Params => MBean.Params, Scope => MBean.Scope); end; MBean.Name := Empty; MBean.Class := Empty; MBean.Scope := REQUEST_SCOPE; MBean.Params := Empty_Params; end case; end Set_Member; MBean_Mapping : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the managed bean definitions. -- ------------------------------ package body Reader_Config is begin Reader.Add_Mapping ("faces-config", MBean_Mapping'Access); Reader.Add_Mapping ("module", MBean_Mapping'Access); Reader.Add_Mapping ("web-app", MBean_Mapping'Access); Config.Factory := Factory; Config.Context := Context; Config_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; begin -- <managed-bean> mapping MBean_Mapping.Add_Mapping ("managed-bean", FIELD_MANAGED_BEAN); MBean_Mapping.Add_Mapping ("managed-bean/managed-bean-name", FIELD_NAME); MBean_Mapping.Add_Mapping ("managed-bean/managed-bean-class", FIELD_CLASS); MBean_Mapping.Add_Mapping ("managed-bean/managed-bean-scope", FIELD_SCOPE); MBean_Mapping.Add_Mapping ("managed-bean/managed-property/property-name", FIELD_PROPERTY_NAME); MBean_Mapping.Add_Mapping ("managed-bean/managed-property/value", FIELD_PROPERTY_VALUE); MBean_Mapping.Add_Mapping ("managed-bean/managed-property/property-class", FIELD_PROPERTY_CLASS); MBean_Mapping.Add_Mapping ("managed-bean/managed-property", FIELD_PROPERTY); end ASF.Beans.Mappers;
----------------------------------------------------------------------- -- asf-beans-mappers -- Read XML managed bean declaratiosn -- Copyright (C) 2010, 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ASF.Beans.Mappers is Empty : constant Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (String '("")); Empty_Params : ASF.Beans.Parameter_Bean_Ref.Ref; -- ------------------------------ -- Set the field identified by <b>Field</b> with the <b>Value</b>. -- ------------------------------ procedure Set_Member (MBean : in out Managed_Bean; Field : in Managed_Bean_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => MBean.Name := Value; when FIELD_CLASS => MBean.Class := Value; when FIELD_SCOPE => declare Scope : constant String := Util.Beans.Objects.To_String (Value); begin if Scope = "request" then MBean.Scope := REQUEST_SCOPE; elsif Scope = "session" then MBean.Scope := SESSION_SCOPE; elsif Scope = "application" then MBean.Scope := APPLICATION_SCOPE; else raise Util.Serialize.Mappers.Field_Error with "Invalid scope: " & Scope; end if; end; when FIELD_PROPERTY_NAME => MBean.Prop_Name := Value; when FIELD_PROPERTY_VALUE => MBean.Prop_Value := Value; when FIELD_PROPERTY_CLASS => null; when FIELD_PROPERTY => -- Create the parameter list only the first time a property is seen. if MBean.Params.Is_Null then MBean.Params := ASF.Beans.Parameter_Bean_Ref.Create (new ASF.Beans.Parameter_Bean); end if; -- Add the parameter. The property value is parsed as an EL expression. EL.Beans.Add_Parameter (MBean.Params.Value.all.Params, Util.Beans.Objects.To_String (MBean.Prop_Name), Util.Beans.Objects.To_String (MBean.Prop_Value), MBean.Context.all); MBean.Prop_Name := Empty; MBean.Prop_Value := Empty; when FIELD_MANAGED_BEAN => declare Name : constant String := Util.Beans.Objects.To_String (MBean.Name); Class : constant String := Util.Beans.Objects.To_String (MBean.Class); begin Register (Factory => MBean.Factory.all, Name => Name, Class => Class, Params => MBean.Params, Scope => MBean.Scope); end; MBean.Name := Empty; MBean.Class := Empty; MBean.Scope := REQUEST_SCOPE; MBean.Params := Empty_Params; end case; end Set_Member; MBean_Mapping : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the managed bean definitions. -- ------------------------------ package body Reader_Config is begin Mapper.Add_Mapping ("faces-config", MBean_Mapping'Access); Mapper.Add_Mapping ("module", MBean_Mapping'Access); Mapper.Add_Mapping ("web-app", MBean_Mapping'Access); Config.Factory := Factory; Config.Context := Context; Config_Mapper.Set_Context (Mapper, Config'Unchecked_Access); end Reader_Config; begin -- <managed-bean> mapping MBean_Mapping.Add_Mapping ("managed-bean", FIELD_MANAGED_BEAN); MBean_Mapping.Add_Mapping ("managed-bean/managed-bean-name", FIELD_NAME); MBean_Mapping.Add_Mapping ("managed-bean/managed-bean-class", FIELD_CLASS); MBean_Mapping.Add_Mapping ("managed-bean/managed-bean-scope", FIELD_SCOPE); MBean_Mapping.Add_Mapping ("managed-bean/managed-property/property-name", FIELD_PROPERTY_NAME); MBean_Mapping.Add_Mapping ("managed-bean/managed-property/value", FIELD_PROPERTY_VALUE); MBean_Mapping.Add_Mapping ("managed-bean/managed-property/property-class", FIELD_PROPERTY_CLASS); MBean_Mapping.Add_Mapping ("managed-bean/managed-property", FIELD_PROPERTY); end ASF.Beans.Mappers;
Update the Reader_Config to use the new parser/mapper interface
Update the Reader_Config to use the new parser/mapper interface
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b7d43e6564a94a14042d4d49ace6dc4cf3a03e37
mat/src/mat-readers-marshaller.adb
mat/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with MAT.Types; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer := To_Pointer (Buffer.Current + Storage_Offset (1)); Low : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size <= 1 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size < 4 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 4; Buffer.Current := Buffer.Current + Storage_Offset (4); if Buffer.Current >= Buffer.Last then Buffer.Current := Buffer.Start; end if; return P.all; end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => pragma Assert (False, "Invalid attribute type "); return 0; end case; end Get_Target_Value; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with MAT.Types; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer := To_Pointer (Buffer.Current + Storage_Offset (1)); Low : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size <= 1 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size < 4 then raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 4; Buffer.Current := Buffer.Current + Storage_Offset (4); if Buffer.Current >= Buffer.Last then Buffer.Current := Buffer.Start; end if; return P.all; end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => pragma Assert (False, "Invalid attribute type "); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; end MAT.Readers.Marshaller;
Implement the Get_String operation
Implement the Get_String operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
facd38226e108132cf71ab66354559dd30b0cf5b
src/ado-drivers.adb
src/ado-drivers.adb
----------------------------------------------------------------------- -- 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 Ada.IO_Exceptions; with ADO.Queries.Loaders; package body ADO.Drivers is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin Global_Config := Util.Properties.Manager (Config); -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Global_Config.Get ("ado.queries.paths", ".;db"), Global_Config.Get ("ado.queries.load", "false") = "true"); ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Name : in String; Default : in String := "") return String is begin return Global_Config.Get (Name, Default); end Get_Config; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
----------------------------------------------------------------------- -- 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 Ada.IO_Exceptions; with ADO.Queries.Loaders; package body ADO.Drivers is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin Global_Config := Util.Properties.Manager (Config); -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Global_Config.Get ("ado.queries.paths", ".;db"), Global_Config.Get ("ado.queries.load", "false") = "true"); -- Initialize the drivers. ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Name : in String; Default : in String := "") return String is begin return Global_Config.Get (Name, Default); end Get_Config; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
Add some comments
Add some comments
Ada
apache-2.0
Letractively/ada-ado
feb991e4ad33d6358c52100b4f085a8cf1f93c67
testutil/ahven/ahven-framework.ads
testutil/ahven/ahven-framework.ads
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Finalization; with Ahven; with Ahven.Listeners; with Ahven.SList; with Ahven.AStrings; pragma Elaborate_All (Ahven); pragma Elaborate_All (Ahven.SList); package Ahven.Framework is Three_Hours : constant := 10800.0; subtype Test_Duration is Duration range 0.0 .. Three_Hours; type Test_Count_Type is new Natural; -- Type for the test count. This effectively -- limits the amount tests to whatever Natural is. -- -- Although, in practice when adding tests the limit -- is not checked. type Test is abstract new Ada.Finalization.Controlled with null record; -- A type, which provides the base for Test_Case and -- Test_Suite types. type Test_Class_Access is access all Test'Class; procedure Set_Up (T : in out Test); -- Set_Up is called before executing the test procedure. -- -- By default, the procedure does nothing, but derived -- types can overwrite this method and add their own -- customisations. -- -- One should not call this explicitly by herself. -- The framework calls it when necessary. procedure Tear_Down (T : in out Test); -- Tear_Down is called after the test procedure is executed. -- -- By default, the procedure does nothing, but derived -- types can overwrite this method and add their own -- customisations. -- -- One should not call this explicitly by herself. -- The framework calls it when necessary. function Get_Name (T : Test) return String is abstract; -- Return the name of the test. -- -- Types derived from the Test type are required to overwrite -- this procedure. procedure Run (T : in out Test; Listener : in out Listeners.Result_Listener'Class); -- Run the test and place the test result to Result. -- -- Calls Run (T, Listener, Timeout) with Timeout value 0.0. procedure Run (T : in out Test; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration) is abstract; -- Run the test and place the test result to Result. -- Timeout specifies the maximum runtime for a single test. -- -- Types derived from the Test type are required to overwrite -- this procedure. procedure Run (T : in out Test; Test_Name : String; Listener : in out Listeners.Result_Listener'Class); -- Run the test and place the test result to Result. -- -- Calls Run (T, Test_Name, Listener, Timeout) with Timeout value 0.0. procedure Run (T : in out Test; Test_Name : String; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration) is abstract; -- Run the test with given name and place the test result to Result. -- Timeout specifies the maximum runtime for a single test. -- Notice: If multiple tests have same name this might call all of -- them. -- -- Types derived from the Test type are required to overwrite -- this procedure. function Test_Count (T : Test) return Test_Count_Type is abstract; -- Return the amount of tests (test routines) which will be executed when -- the Run (T) procedure is called. function Test_Count (T : Test; Test_Name : String) return Test_Count_Type is abstract; -- Return the amount of tests (test routines) which will be executed when -- the Run (T, Test_Name) procedure is called. procedure Execute (T : in out Test'Class; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Call Test class' Run method and place the test outcome to Result. -- The procedure calls Start_Test of every listener before calling -- the Run procedure and End_Test after calling the Run procedure. -- -- This procedure is meant to be called from Runner package(s). -- There should be no need for other to use this. procedure Execute (T : in out Test'Class; Test_Name : String; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Same as Execute above, but call the Run procedure which -- takes Test_Name parameter. type Test_Case is abstract new Test with private; -- The base type for other test cases. function Get_Name (T : Test_Case) return String; -- Return the name of the test case. procedure Run (T : in out Test_Case; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Run Test_Case's test routines. procedure Run (T : in out Test_Case; Test_Name : String; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Run Test_Case's test routine which matches to the Name. function Test_Count (T : Test_Case) return Test_Count_Type; -- Implementation of Test_Count (T : Test). function Test_Count (T : Test_Case; Test_Name : String) return Test_Count_Type; -- Implementation of Test_Count (T : Test, Test_Name : String). procedure Finalize (T : in out Test_Case); -- Finalize procedure of the Test_Case. procedure Set_Name (T : in out Test_Case; Name : String); -- Set Test_Case's name. -- -- If longer than 160 characters, the name is truncated -- to 160 characters. type Object_Test_Routine_Access is access procedure (T : in out Test_Case'Class); -- A pointer to a test routine which takes Test_Case'Class object -- as an argument. -- -- For this kind of test routines, the framework will -- call Set_Up and Tear_Down routines before and after -- test routine execution. type Simple_Test_Routine_Access is access procedure; -- A pointer to a test routine which does not take arguments. procedure Add_Test_Routine (T : in out Test_Case'Class; Routine : Object_Test_Routine_Access; Name : String); -- Register a test routine to the Test_Case object. -- -- The routine must have signature -- "procedure R (T : in out Test_Case'Class)". procedure Add_Test_Routine (T : in out Test_Case'Class; Routine : Simple_Test_Routine_Access; Name : String); -- Register a simple test routine to the Test_Case. -- -- The routine must have signature -- "procedure R". type Test_Suite is new Test with private; -- A collection of Tests. -- -- You can either fill a Test_Suite object with Test_Case objects -- or nest multiple Test_Suite objects. You can even mix -- Test_Case and Test_Suite objects, if necessary. type Test_Suite_Access is access all Test_Suite; function Create_Suite (Suite_Name : String) return Test_Suite_Access; -- Create a new Test_Suite. -- Caller must free the returned Test_Suite using Release_Suite. function Create_Suite (Suite_Name : String) return Test_Suite; -- Create a new Test_Suite. The suite and its children are -- released automatically. procedure Add_Test (Suite : in out Test_Suite; T : Test_Class_Access); -- Add a Test to the suite. The suite frees the Test automatically -- when it is no longer needed. procedure Add_Test (Suite : in out Test_Suite; T : Test_Suite_Access); -- Add a Test suite to the suite. The suite frees the Test automatically -- when it is no longer needed. -- -- This is a helper function, which internally calls -- Add_Test (Suite : in out Test_Suite; T : Test_Class_Access). procedure Add_Static_Test (Suite : in out Test_Suite; T : Test'Class); -- Add a Test to the suite. This procedure is meant for statically -- allocated Test_Case objects. -- -- Please note, that a copy of the Test'Class object is saved to -- the suite. Original test object is not modified and changes -- made to it after adding the test are not propagated to -- the added object. function Get_Name (T : Test_Suite) return String; -- Return the name of Test_Suite. procedure Run (T : in out Test_Suite; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Run Test_Suite's Test_Cases. procedure Run (T : in out Test_Suite; Test_Name : String; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Run test suite's child which matches to the given name. function Test_Count (T : Test_Suite) return Test_Count_Type; -- Implementation of Test_Count (T : Test). function Test_Count (T : Test_Suite; Test_Name : String) return Test_Count_Type; -- Implementation of Test_Count (T : Test, Test_Name : String). procedure Adjust (T : in out Test_Suite); -- Adjust procedure of Test_Suite. -- Handles the copying of the structure properly procedure Finalize (T : in out Test_Suite); -- Finalize procedure of Test_Suite. Frees all added Tests. procedure Release_Suite (T : Test_Suite_Access); -- Release the memory of Test_Suite. -- All added tests are released automatically. private type Command_Object_Enum is (SIMPLE, OBJECT); type Test_Command (Command_Kind : Command_Object_Enum := SIMPLE) is record Name : AStrings.Bounded_String; case Command_Kind is when SIMPLE => Simple_Routine : Simple_Test_Routine_Access; when OBJECT => Object_Routine : Object_Test_Routine_Access; end case; end record; -- Name attribute tells the name of the test routine. procedure Run (Command : Test_Command; T : in out Test_Case'Class); -- Run the specified command. -- Calls Set_Up and Tear_Down if necessary. package Test_Command_List is new Ahven.SList (Element_Type => Test_Command); type Test_Case is abstract new Test with record Routines : Test_Command_List.List := Test_Command_List.Empty_List; Name : AStrings.Bounded_String := AStrings.Null_Bounded_String; end record; -- Our test case type. It holds a list of test routines -- (test command objects) and the name of the test case. procedure Run_Command (Command : Test_Command; Info : Listeners.Context; Timeout : Test_Duration; Listener : in out Listeners.Result_Listener'Class; T : in out Test_Case'Class); -- Handle dispatching to the right Run (Command : Test_Command) -- procedure and record test routine result to the Result object. -- -- Timeout parameter defines the longest time the test is allowed -- to run. Value 0.0 means infinite time. type Test_Class_Wrapper is record Ptr : Test_Class_Access; end record; package Test_List is new Ahven.SList (Element_Type => Test_Class_Wrapper); package Indefinite_Test_List is type List is new Ada.Finalization.Controlled with private; Empty_List : constant List; procedure Append (Target : in out List; Node_Data : Test'Class); -- Append an element at the end of the list. procedure Clear (Target : in out List); -- Remove all elements from the list. generic with procedure Action (T : in out Test'Class) is <>; procedure For_Each (Target : List); -- A generic procedure for walk through every item -- in the list and call Action procedure for them. private type Node; type Node_Access is access Node; procedure Remove (Ptr : Node_Access); -- A procedure to release memory pointed by Ptr. type Node is record Next : Node_Access := null; Data : Test_Class_Access := null; end record; type List is new Ada.Finalization.Controlled with record First : Node_Access := null; Last : Node_Access := null; end record; procedure Initialize (Target : in out List); procedure Finalize (Target : in out List); procedure Adjust (Target : in out List); Empty_List : constant List := (Ada.Finalization.Controlled with First => null, Last => null); end Indefinite_Test_List; type Test_Suite is new Test with record Suite_Name : AStrings.Bounded_String := AStrings.Null_Bounded_String; Test_Cases : Test_List.List := Test_List.Empty_List; Static_Test_Cases : Indefinite_Test_List.List := Indefinite_Test_List.Empty_List; end record; -- A suite type which holds a list of test cases and the name -- of the suite. end Ahven.Framework;
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Finalization; with Ahven; with Ahven.Listeners; with Ahven.SList; with Ahven.AStrings; pragma Elaborate_All (Ahven); pragma Elaborate_All (Ahven.SList); package Ahven.Framework is Three_Hours : constant := 10800.0; subtype Test_Duration is Duration range 0.0 .. Three_Hours; type Test_Count_Type is new Natural; -- Type for the test count. This effectively -- limits the amount tests to whatever Natural is. -- -- Although, in practice when adding tests the limit -- is not checked. type Test is abstract new Ada.Finalization.Controlled with null record; -- A type, which provides the base for Test_Case and -- Test_Suite types. type Test_Class_Access is access all Test'Class; procedure Set_Up (T : in out Test); -- Set_Up is called before executing the test procedure. -- -- By default, the procedure does nothing, but derived -- types can overwrite this method and add their own -- customisations. -- -- One should not call this explicitly by herself. -- The framework calls it when necessary. procedure Tear_Down (T : in out Test); -- Tear_Down is called after the test procedure is executed. -- -- By default, the procedure does nothing, but derived -- types can overwrite this method and add their own -- customisations. -- -- One should not call this explicitly by herself. -- The framework calls it when necessary. function Get_Name (T : Test) return String is abstract; -- Return the name of the test. -- -- Types derived from the Test type are required to overwrite -- this procedure. procedure Run (T : in out Test; Listener : in out Listeners.Result_Listener'Class); -- Run the test and place the test result to Result. -- -- Calls Run (T, Listener, Timeout) with Timeout value 0.0. procedure Run (T : in out Test; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration) is abstract; -- Run the test and place the test result to Result. -- Timeout specifies the maximum runtime for a single test. -- -- Types derived from the Test type are required to overwrite -- this procedure. procedure Run (T : in out Test; Test_Name : String; Listener : in out Listeners.Result_Listener'Class); -- Run the test and place the test result to Result. -- -- Calls Run (T, Test_Name, Listener, Timeout) with Timeout value 0.0. procedure Run (T : in out Test; Test_Name : String; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration) is abstract; -- Run the test with given name and place the test result to Result. -- Timeout specifies the maximum runtime for a single test. -- Notice: If multiple tests have same name this might call all of -- them. -- -- Types derived from the Test type are required to overwrite -- this procedure. function Test_Count (T : Test) return Test_Count_Type is abstract; -- Return the amount of tests (test routines) which will be executed when -- the Run (T) procedure is called. function Test_Count (T : Test; Test_Name : String) return Test_Count_Type is abstract; -- Return the amount of tests (test routines) which will be executed when -- the Run (T, Test_Name) procedure is called. procedure Execute (T : in out Test'Class; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Call Test class' Run method and place the test outcome to Result. -- The procedure calls Start_Test of every listener before calling -- the Run procedure and End_Test after calling the Run procedure. -- -- This procedure is meant to be called from Runner package(s). -- There should be no need for other to use this. procedure Execute (T : in out Test'Class; Test_Name : String; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Same as Execute above, but call the Run procedure which -- takes Test_Name parameter. type Test_Case is abstract new Test with private; -- The base type for other test cases. function Get_Name (T : Test_Case) return String; -- Return the name of the test case. procedure Run (T : in out Test_Case; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Run Test_Case's test routines. procedure Run (T : in out Test_Case; Test_Name : String; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Run Test_Case's test routine which matches to the Name. function Test_Count (T : Test_Case) return Test_Count_Type; -- Implementation of Test_Count (T : Test). function Test_Count (T : Test_Case; Test_Name : String) return Test_Count_Type; -- Implementation of Test_Count (T : Test, Test_Name : String). procedure Finalize (T : in out Test_Case); -- Finalize procedure of the Test_Case. procedure Set_Name (T : in out Test_Case; Name : String); -- Set Test_Case's name. -- -- If longer than 160 characters, the name is truncated -- to 160 characters. type Object_Test_Routine_Access is access procedure (T : in out Test_Case'Class); -- A pointer to a test routine which takes Test_Case'Class object -- as an argument. -- -- For this kind of test routines, the framework will -- call Set_Up and Tear_Down routines before and after -- test routine execution. type Simple_Test_Routine_Access is access procedure; -- A pointer to a test routine which does not take arguments. procedure Add_Test_Routine (T : in out Test_Case'Class; Routine : Object_Test_Routine_Access; Name : String); -- Register a test routine to the Test_Case object. -- -- The routine must have signature -- "procedure R (T : in out Test_Case'Class)". procedure Add_Test_Routine (T : in out Test_Case'Class; Routine : Simple_Test_Routine_Access; Name : String); -- Register a simple test routine to the Test_Case. -- -- The routine must have signature -- "procedure R". type Test_Suite is new Test with private; -- A collection of Tests. -- -- You can either fill a Test_Suite object with Test_Case objects -- or nest multiple Test_Suite objects. You can even mix -- Test_Case and Test_Suite objects, if necessary. type Test_Suite_Access is access all Test_Suite; function Create_Suite (Suite_Name : String) return Test_Suite_Access; -- Create a new Test_Suite. -- Caller must free the returned Test_Suite using Release_Suite. function Create_Suite (Suite_Name : String) return Test_Suite; -- Create a new Test_Suite. The suite and its children are -- released automatically. procedure Add_Test (Suite : in out Test_Suite; T : Test_Class_Access); -- Add a Test to the suite. The suite frees the Test automatically -- when it is no longer needed. procedure Add_Test (Suite : in out Test_Suite; T : Test_Suite_Access); -- Add a Test suite to the suite. The suite frees the Test automatically -- when it is no longer needed. -- -- This is a helper function, which internally calls -- Add_Test (Suite : in out Test_Suite; T : Test_Class_Access). procedure Add_Static_Test (Suite : in out Test_Suite; T : Test'Class); -- Add a Test to the suite. This procedure is meant for statically -- allocated Test_Case objects. -- -- Please note, that a copy of the Test'Class object is saved to -- the suite. Original test object is not modified and changes -- made to it after adding the test are not propagated to -- the added object. function Get_Name (T : Test_Suite) return String; -- Return the name of Test_Suite. procedure Run (T : in out Test_Suite; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Run Test_Suite's Test_Cases. procedure Run (T : in out Test_Suite; Test_Name : String; Listener : in out Listeners.Result_Listener'Class; Timeout : Test_Duration); -- Run test suite's child which matches to the given name. function Test_Count (T : Test_Suite) return Test_Count_Type; -- Implementation of Test_Count (T : Test). function Test_Count (T : Test_Suite; Test_Name : String) return Test_Count_Type; -- Implementation of Test_Count (T : Test, Test_Name : String). procedure Adjust (T : in out Test_Suite); -- Adjust procedure of Test_Suite. -- Handles the copying of the structure properly procedure Finalize (T : in out Test_Suite); -- Finalize procedure of Test_Suite. Frees all added Tests. procedure Release_Suite (T : Test_Suite_Access); -- Release the memory of Test_Suite. -- All added tests are released automatically. procedure Set_Logging (Flag : in Boolean); -- Enable or disable traces before/after test execution. private type Command_Object_Enum is (SIMPLE, OBJECT); type Test_Command (Command_Kind : Command_Object_Enum := SIMPLE) is record Name : AStrings.Bounded_String; case Command_Kind is when SIMPLE => Simple_Routine : Simple_Test_Routine_Access; when OBJECT => Object_Routine : Object_Test_Routine_Access; end case; end record; -- Name attribute tells the name of the test routine. procedure Run (Command : Test_Command; T : in out Test_Case'Class); -- Run the specified command. -- Calls Set_Up and Tear_Down if necessary. package Test_Command_List is new Ahven.SList (Element_Type => Test_Command); type Test_Case is abstract new Test with record Routines : Test_Command_List.List := Test_Command_List.Empty_List; Name : AStrings.Bounded_String := AStrings.Null_Bounded_String; end record; -- Our test case type. It holds a list of test routines -- (test command objects) and the name of the test case. procedure Run_Command (Command : Test_Command; Info : Listeners.Context; Timeout : Test_Duration; Listener : in out Listeners.Result_Listener'Class; T : in out Test_Case'Class); -- Handle dispatching to the right Run (Command : Test_Command) -- procedure and record test routine result to the Result object. -- -- Timeout parameter defines the longest time the test is allowed -- to run. Value 0.0 means infinite time. type Test_Class_Wrapper is record Ptr : Test_Class_Access; end record; package Test_List is new Ahven.SList (Element_Type => Test_Class_Wrapper); package Indefinite_Test_List is type List is new Ada.Finalization.Controlled with private; Empty_List : constant List; procedure Append (Target : in out List; Node_Data : Test'Class); -- Append an element at the end of the list. procedure Clear (Target : in out List); -- Remove all elements from the list. generic with procedure Action (T : in out Test'Class) is <>; procedure For_Each (Target : List); -- A generic procedure for walk through every item -- in the list and call Action procedure for them. private type Node; type Node_Access is access Node; procedure Remove (Ptr : Node_Access); -- A procedure to release memory pointed by Ptr. type Node is record Next : Node_Access := null; Data : Test_Class_Access := null; end record; type List is new Ada.Finalization.Controlled with record First : Node_Access := null; Last : Node_Access := null; end record; procedure Initialize (Target : in out List); procedure Finalize (Target : in out List); procedure Adjust (Target : in out List); Empty_List : constant List := (Ada.Finalization.Controlled with First => null, Last => null); end Indefinite_Test_List; type Test_Suite is new Test with record Suite_Name : AStrings.Bounded_String := AStrings.Null_Bounded_String; Test_Cases : Test_List.List := Test_List.Empty_List; Static_Test_Cases : Indefinite_Test_List.List := Indefinite_Test_List.Empty_List; end record; -- A suite type which holds a list of test cases and the name -- of the suite. end Ahven.Framework;
Declare the Set_Logging procedure
Declare the Set_Logging procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
91fbdfb305ba60807378e86286243327890cb111
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Document the policy and policy manager
Document the policy and policy manager
Ada
apache-2.0
stcarrez/ada-security
ac23d263466d1991e82e692c612a0d050569ea6a
mat/src/mat-formats.adb
mat/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Formats is -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin return Hex; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Formats is Hex_Prefix : Boolean := True; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; end MAT.Formats;
Add support to print an optional 0x prefix to addresses
Add support to print an optional 0x prefix to addresses
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f62b56e9b14d0f740f24fc5bc7dbb586e357d47b
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; 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;
------------------------------------------------------------------------------ -- 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; function Elements (Set : in Atom_Set) return Atom_Array_Refs.Immutable_Reference; 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; function Elements (Set : in Atom_Set) return Atom_Array_Refs.Immutable_Reference is (Set.Elements); 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 an accessor to the array underlying an atom set
containers: add an accessor to the array underlying an atom set
Ada
isc
faelys/natools-web,faelys/natools-web
84a17794121f7802a34324ec235faa42cdab4be6
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. The realm also returns in the grant the user principal that -- identifies the user. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is -- Minimum length for the server private key (160 bits min length). -- (See NIST Special Publication 800-107) MIN_KEY_LENGTH : constant Positive := 20; Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String; Decode : in Boolean := False); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- The <tt>Token</tt> procedure is the main entry point to get the access token and -- refresh token. The request parameters are accessed through the <tt>Params</tt> interface. -- The operation looks at the "grant_type" parameter to identify the access method. -- It also looks at the "client_id" to find the application for which the access token -- is created. Upon successful authentication, the operation returns a grant. procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Create a HMAC-SHA1 of the data with the private key. -- This function can be overriden to use another signature algorithm. function Sign (Realm : in Auth_Manager; Data : in String) return String; -- Forge an access token. The access token is signed by an HMAC-SHA1 signature. -- The returned token is formed as follows: -- <expiration>.<ident>.HMAC-SHA1(<private-key>, <expiration>.<ident>) -- See also RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; -- Decode the expiration date that was extracted from the token. function Parse_Expire (Expire : in String) return Ada.Calendar.Time; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017, 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.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. The realm also returns in the grant the user principal that -- identifies the user. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is -- Minimum length for the server private key (160 bits min length). -- (See NIST Special Publication 800-107) MIN_KEY_LENGTH : constant Positive := 20; Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- The token expiration date in seconds. Expires_In : Duration := 0.0; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String; Decode : in Boolean := False); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- The <tt>Token</tt> procedure is the main entry point to get the access token and -- refresh token. The request parameters are accessed through the <tt>Params</tt> interface. -- The operation looks at the "grant_type" parameter to identify the access method. -- It also looks at the "client_id" to find the application for which the access token -- is created. Upon successful authentication, the operation returns a grant. procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Create a HMAC-SHA1 of the data with the private key. -- This function can be overriden to use another signature algorithm. function Sign (Realm : in Auth_Manager; Data : in String) return String; -- Forge an access token. The access token is signed by an HMAC-SHA1 signature. -- The returned token is formed as follows: -- <expiration>.<ident>.HMAC-SHA1(<private-key>, <expiration>.<ident>) -- See also RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; -- Decode the expiration date that was extracted from the token. function Parse_Expire (Expire : in String) return Ada.Calendar.Time; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Add Expires_In member to the Grant_Type
Add Expires_In member to the Grant_Type
Ada
apache-2.0
stcarrez/ada-security
9080903a17d57c7d8d25c4acd665410773a6a3e6
src/wiki-plugins-variables.adb
src/wiki-plugins-variables.adb
----------------------------------------------------------------------- -- wiki-plugins-variables -- Variables plugin -- 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 Wiki.Filters.Variables; package body Wiki.Plugins.Variables is -- ------------------------------ -- Set or update a variable in the `Wiki.Filters.Variable` filter. -- ------------------------------ overriding procedure Expand (Plugin : in out Variable_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is pragma Unreferenced (Plugin, Document); begin if Wiki.Attributes.Length (Params) >= 3 then declare First : Wiki.Attributes.Cursor := Wiki.Attributes.First (Params); Second : Wiki.Attributes.Cursor; begin Wiki.Attributes.Next (First); Second := First; Wiki.Attributes.Next (Second); Wiki.Filters.Variables.Add_Variable (Context.Filters, Wiki.Attributes.Get_Wide_Value (First), Wiki.Attributes.Get_Wide_Value (Second)); end; end if; end Expand; -- ------------------------------ -- List the variables from the `Wiki.Filters.Variable` filter. -- ------------------------------ overriding procedure Expand (Plugin : in out List_Variable_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is pragma Unreferenced (Plugin); procedure Print_Variable (Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); Has_Table : Boolean := False; Format : Format_Map := (others => False); Attributes : Wiki.Attributes.Attribute_List; procedure Print_Variable (Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is begin Has_Table := True; Context.Filters.Add_Row (Document); Context.Filters.Add_Column (Document, Attributes); Context.Filters.Add_Text (Document, Name, Format); Context.Filters.Add_Column (Document, Attributes); Context.Filters.Add_Text (Document, Value, Format); end Print_Variable; begin Wiki.Filters.Variables.Iterate (Context.Filters, Print_Variable'Access); if Has_Table then Context.Filters.Finish_Table (Document); end if; end Expand; end Wiki.Plugins.Variables;
----------------------------------------------------------------------- -- wiki-plugins-variables -- Variables plugin -- 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 Wiki.Filters.Variables; package body Wiki.Plugins.Variables is -- ------------------------------ -- Set or update a variable in the `Wiki.Filters.Variable` filter. -- ------------------------------ overriding procedure Expand (Plugin : in out Variable_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is pragma Unreferenced (Plugin, Document); begin if Wiki.Attributes.Length (Params) >= 3 then declare First : Wiki.Attributes.Cursor := Wiki.Attributes.First (Params); Second : Wiki.Attributes.Cursor; begin Wiki.Attributes.Next (First); Second := First; Wiki.Attributes.Next (Second); Wiki.Filters.Variables.Add_Variable (Context.Filters, Wiki.Attributes.Get_Wide_Value (First), Wiki.Attributes.Get_Wide_Value (Second)); end; end if; end Expand; -- ------------------------------ -- List the variables from the `Wiki.Filters.Variable` filter. -- ------------------------------ overriding procedure Expand (Plugin : in out List_Variable_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in out Plugin_Context) is pragma Unreferenced (Plugin); procedure Print_Variable (Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); Has_Table : Boolean := False; Format : constant Format_Map := (others => False); Attributes : Wiki.Attributes.Attribute_List; procedure Print_Variable (Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is begin Has_Table := True; Context.Filters.Add_Row (Document); Context.Filters.Add_Column (Document, Attributes); Context.Filters.Add_Text (Document, Name, Format); Context.Filters.Add_Column (Document, Attributes); Context.Filters.Add_Text (Document, Value, Format); end Print_Variable; begin Wiki.Filters.Variables.Iterate (Context.Filters, Print_Variable'Access); if Has_Table then Context.Filters.Finish_Table (Document); end if; end Expand; end Wiki.Plugins.Variables;
Change Format local variable to a constant
Change Format local variable to a constant
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
65804b17cbb141f8dffecf05ca5d9755b942cf7a
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with Wiki.Strings; with AWA.Modules; with AWA.Blogs.Models; with AWA.Counters.Definition; with Security.Permissions; -- == Integration == -- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application. -- It provides operations that are used by the blog beans or other services to create and update -- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- type Application is new AWA.Applications.Application with record -- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Blogs.Modules.NAME, -- URI => "blogs", -- Module => App.Blog_Module'Access); -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Define the read post counter. package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Get the image prefix that was configured for the Blog module. function Get_Image_Prefix (Module : in Blog_Module) return Wiki.Strings.UString; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private type Blog_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; end record; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with Wiki.Strings; with AWA.Modules; with AWA.Blogs.Models; with AWA.Counters.Definition; with AWA.Blogs.Servlets; with Security.Permissions; -- == Integration == -- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application. -- It provides operations that are used by the blog beans or other services to create and update -- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- type Application is new AWA.Applications.Application with record -- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Blogs.Modules.NAME, -- URI => "blogs", -- Module => App.Blog_Module'Access); -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Define the read post counter. package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Get the image prefix that was configured for the Blog module. function Get_Image_Prefix (Module : in Blog_Module) return Wiki.Strings.UString; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private type Blog_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; Image_Servlet : aliased AWA.Blogs.Servlets.Image_Servlet; end record; end AWA.Blogs.Modules;
Add the Image_Servlet to the Blog_Module type
Add the Image_Servlet to the Blog_Module type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
bcdf0d2b4a3c6961b20e636438dfd8fd9a9f1741
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- 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.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. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; Lib_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 = "-lib" then Lib_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 = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, 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"); Cmd.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."); Cmd.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_Property ("is_lib", Boolean'Image (Lib_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"); elsif Lib_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-lib"); 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. -- ------------------------------ overriding 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|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & "[--lib] [--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 MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses 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"); Put_Line (" --lib Generate a library project"); end Help; end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- 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.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. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; Lib_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: ? -lib -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 = "-lib" then Lib_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 = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, 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"); Cmd.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."); Cmd.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_Property ("is_lib", Boolean'Image (Lib_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"); elsif Lib_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-lib"); 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. -- ------------------------------ overriding 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|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & " [--lib] [--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 MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses 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"); Put_Line (" --lib Generate a library project"); end Help; end Gen.Commands.Project;
Add missing --lib option to the Getopt operation for create-project command
Add missing --lib option to the Getopt operation for create-project command
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
9c71b96e269af43366d8dcd500acf1af6ef60ac9
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Storages.Models; with ADO.Objects; with ADO.Sessions; with ADO.Statements; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX); begin Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix)); end Configure; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Workspaces.Modules.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id, List => (ACL_Delete_Blog.Permission, ACL_Update_Post.Permission, ACL_Create_Post.Permission, ACL_Delete_Post.Permission)); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; -- ------------------------------ -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. -- ------------------------------ procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref) is pragma Unreferenced (Model); use type AWA.Storages.Models.Storage_Type; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement; Kind : AWA.Storages.Models.Storage_Type; begin if Width = Natural'Last or Height = Natural'Last then Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); elsif Width > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data); Query.Bind_Param ("width", Width); elsif Height > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data); Query.Bind_Param ("height", Height); else Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); end if; Query.Bind_Param ("post_id", Post_Id); Query.Bind_Param ("store_id", Image_Id); Query.Bind_Param ("user_id", User); Query.Execute; if not Query.Has_Elements then Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id)); raise ADO.Objects.NOT_FOUND; end if; Mime := Query.Get_Unbounded_String (0); Date := Query.Get_Time (1); Width := Query.Get_Natural (4); Height := Query.Get_Natural (5); Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3)); if Kind = AWA.Storages.Models.DATABASE then Into := Query.Get_Blob (6); else null; end if; end Load_Image; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Storages.Models; with ADO.Objects; with ADO.Sessions; with ADO.Statements; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX); begin Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix)); end Configure; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Get the image prefix that was configured for the Blog module. -- ------------------------------ function Get_Image_Prefix (Module : in Blog_Module) return Wiki.Strings.UString is begin return Module.Image_Prefix; end Get_Image_Prefix; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Workspaces.Modules.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id, List => (ACL_Delete_Blog.Permission, ACL_Update_Post.Permission, ACL_Create_Post.Permission, ACL_Delete_Post.Permission)); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; -- ------------------------------ -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. -- ------------------------------ procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref) is pragma Unreferenced (Model); use type AWA.Storages.Models.Storage_Type; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement; Kind : AWA.Storages.Models.Storage_Type; begin if Width = Natural'Last or Height = Natural'Last then Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); elsif Width > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data); Query.Bind_Param ("width", Width); elsif Height > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data); Query.Bind_Param ("height", Height); else Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); end if; Query.Bind_Param ("post_id", Post_Id); Query.Bind_Param ("store_id", Image_Id); Query.Bind_Param ("user_id", User); Query.Execute; if not Query.Has_Elements then Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id)); raise ADO.Objects.NOT_FOUND; end if; Mime := Query.Get_Unbounded_String (0); Date := Query.Get_Time (1); Width := Query.Get_Natural (4); Height := Query.Get_Natural (5); Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3)); if Kind = AWA.Storages.Models.DATABASE then Into := Query.Get_Blob (6); else null; end if; end Load_Image; end AWA.Blogs.Modules;
Implement the Get_Image_Prefix function
Implement the Get_Image_Prefix function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
971fb69ef87c65ad76452b57d8e5285f93898f4c
regtests/util-dates-tests.adb
regtests/util-dates-tests.adb
----------------------------------------------------------------------- -- util-dates-tests - Test for dates -- Copyright (C) 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Dates.ISO8601; package body Util.Dates.Tests is package Caller is new Util.Test_Caller (Test, "Dates"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Image", Test_ISO8601_Image'Access); Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value", Test_ISO8601_Value'Access); end Add_Tests; -- ------------------------------ -- Test converting a date in ISO8601. -- ------------------------------ procedure Test_ISO8601_Image (T : in out Test) is T1 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (1980, 1, 2, 10, 30, 23); begin Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1), "Invalid Image"); Util.Tests.Assert_Equals (T, "1980", ISO8601.Image (T1, ISO8601.YEAR), "Invalid Image (YEAR precision)"); Util.Tests.Assert_Equals (T, "1980-01", ISO8601.Image (T1, ISO8601.MONTH), "Invalid Image (MONTH precision)"); Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1, ISO8601.DAY), "Invalid Image (DAY precision)"); Util.Tests.Assert_Equals (T, "1980-01-02T10", ISO8601.Image (T1, ISO8601.HOUR), "Invalid Image (DAY precision)"); Util.Tests.Assert_Equals (T, "1980-01-02T10:30", ISO8601.Image (T1, ISO8601.MINUTE), "Invalid Image (MINUTE precision)"); Util.Tests.Assert_Equals (T, "1980-01-02T10:30:23", ISO8601.Image (T1, ISO8601.SECOND), "Invalid Image (SECOND precision)"); end Test_ISO8601_Image; -- ------------------------------ -- Test converting a string in ISO8601 into a date. -- ------------------------------ procedure Test_ISO8601_Value (T : in out Test) is Date : Ada.Calendar.Time; Info : Date_Record; begin Date := ISO8601.Value ("1980"); Util.Tests.Assert_Equals (T, "1980-01-01", ISO8601.Image (Date)); Date := ISO8601.Value ("1980-03-04"); Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date)); Date := ISO8601.Value ("1980-12-31"); Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date)); Date := ISO8601.Value ("1980-12-31T11:23"); Util.Tests.Assert_Equals (T, "1980-12-31T11:23", ISO8601.Image (Date, ISO8601.MINUTE)); end Test_ISO8601_Value; end Util.Dates.Tests;
----------------------------------------------------------------------- -- util-dates-tests - Test for dates -- Copyright (C) 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Dates.ISO8601; package body Util.Dates.Tests is package Caller is new Util.Test_Caller (Test, "Dates"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Image", Test_ISO8601_Image'Access); Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value", Test_ISO8601_Value'Access); Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value (Errors)", Test_ISO8601_Error'Access); end Add_Tests; -- ------------------------------ -- Test converting a date in ISO8601. -- ------------------------------ procedure Test_ISO8601_Image (T : in out Test) is T1 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (1980, 1, 2, 10, 30, 23); begin Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1), "Invalid Image"); Util.Tests.Assert_Equals (T, "1980", ISO8601.Image (T1, ISO8601.YEAR), "Invalid Image (YEAR precision)"); Util.Tests.Assert_Equals (T, "1980-01", ISO8601.Image (T1, ISO8601.MONTH), "Invalid Image (MONTH precision)"); Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1, ISO8601.DAY), "Invalid Image (DAY precision)"); Util.Tests.Assert_Equals (T, "1980-01-02T10", ISO8601.Image (T1, ISO8601.HOUR), "Invalid Image (DAY precision)"); Util.Tests.Assert_Equals (T, "1980-01-02T10:30", ISO8601.Image (T1, ISO8601.MINUTE), "Invalid Image (MINUTE precision)"); Util.Tests.Assert_Equals (T, "1980-01-02T10:30:23", ISO8601.Image (T1, ISO8601.SECOND), "Invalid Image (SECOND precision)"); end Test_ISO8601_Image; -- ------------------------------ -- Test converting a string in ISO8601 into a date. -- ------------------------------ procedure Test_ISO8601_Value (T : in out Test) is Date : Ada.Calendar.Time; begin Date := ISO8601.Value ("1980"); Util.Tests.Assert_Equals (T, "1980-01-01", ISO8601.Image (Date)); Date := ISO8601.Value ("1980-02"); Util.Tests.Assert_Equals (T, "1980-02", ISO8601.Image (Date, ISO8601.MONTH)); Date := ISO8601.Value ("1980-03-04"); Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date)); Date := ISO8601.Value ("1980-03-04"); Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date)); Date := ISO8601.Value ("1980-12-31"); Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date)); Date := ISO8601.Value ("19801231"); Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date)); Date := ISO8601.Value ("1980-12-31T11:23"); Util.Tests.Assert_Equals (T, "1980-12-31T11:23", ISO8601.Image (Date, ISO8601.MINUTE)); Date := ISO8601.Value ("1980-12-31T11:23:34"); Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34", ISO8601.Image (Date, ISO8601.SECOND)); Date := ISO8601.Value ("1980-12-31T11:23:34.123"); Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34.123+00:00", ISO8601.Image (Date, ISO8601.SUBSECOND)); Date := ISO8601.Value ("1980-12-31T11:23:34.123+04:30"); -- The date was normalized in GMT Util.Tests.Assert_Equals (T, "1980-12-31T06:53:34.123+00:00", ISO8601.Image (Date, ISO8601.SUBSECOND)); end Test_ISO8601_Value; -- ------------------------------ -- Test value convertion errors. -- ------------------------------ procedure Test_ISO8601_Error (T : in out Test) is procedure Check (Date : in String); procedure Check (Date : in String) is begin declare Unused : constant Ada.Calendar.Time := ISO8601.Value (Date); begin T.Fail ("No exception raised for " & Date); end; exception when Constraint_Error => null; end Check; begin Check (""); Check ("1980-"); Check ("1980:02:03"); Check ("1980-02-03u33:33"); Check ("1980-02-03u33"); Check ("1980-13-44"); Check ("1980-12-00"); Check ("1980-12-03T25:34"); Check ("1980-12-03T10x34"); Check ("1980-12-03T10:34p"); Check ("1980-12-31T11:23:34123"); Check ("1980-12-31T11:23:34,1"); Check ("1980-12-31T11:23:34,12"); Check ("1980-12-31T11:23:34x123"); Check ("1980-12-31T11:23:34.1234"); Check ("1980-12-31T11:23:34Zp"); Check ("1980-12-31T11:23:34+2"); Check ("1980-12-31T11:23:34+23x"); Check ("1980-12-31T11:23:34+99"); Check ("1980-12-31T11:23:34+10:0"); Check ("1980-12-31T11:23:34+10:03x"); end Test_ISO8601_Error; end Util.Dates.Tests;
Add new tests to check parsing errors of ISO dates
Add new tests to check parsing errors of ISO dates
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a39f12e7402a03518ca6f934a448e27e5329c97a
src/asf-components-ajax-includes.ads
src/asf-components-ajax-includes.ads
----------------------------------------------------------------------- -- components-ajax-includes -- AJAX Include component -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Ajax.Includes is ASYNC_ATTR_NAME : constant String := "async"; LAYOUT_ATTR_NAME : constant String := "layout"; SRC_ATTR_NAME : constant String := "src"; -- The <b>ajax:include</b> component allows to include type UIInclude is new ASF.Components.Html.UIHtmlComponent with private; -- Get the HTML layout that must be used for the include container. -- The default layout is a "div". -- Returns "div", "span", "pre", "b". function Get_Layout (UI : in UIInclude; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- The included XHTML file is rendered according to the <b>async</b> attribute: -- -- When <b>async</b> is false, render the specified XHTML file in such a way that inner -- forms will be posted on the included view. -- -- When <b>async</b> is true, trigger an AJAX call to include the specified -- XHTML view when the page is loaded. -- -- overriding procedure Encode_Children (UI : in UIInclude; Context : in out ASF.Contexts.Faces.Faces_Context'Class); private type UIInclude is new ASF.Components.Html.UIHtmlComponent with null record; end ASF.Components.Ajax.Includes;
----------------------------------------------------------------------- -- components-ajax-includes -- AJAX Include component -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Ajax.Includes is -- @attribute -- Defines whether the inclusion is asynchronous or not. -- When true, an AJAX call will be made by the client browser to fetch the content. -- When false, the view is included in the current component tree. ASYNC_ATTR_NAME : constant String := "async"; -- @attribute -- Defines the HTML container element that will contain the included view. LAYOUT_ATTR_NAME : constant String := "layout"; -- @attribute -- Defines the view name to include. SRC_ATTR_NAME : constant String := "src"; -- @tag include -- The <b>ajax:include</b> component allows to include type UIInclude is new ASF.Components.Html.UIHtmlComponent with private; -- Get the HTML layout that must be used for the include container. -- The default layout is a "div". -- Returns "div", "span", "pre", "b". function Get_Layout (UI : in UIInclude; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- The included XHTML file is rendered according to the <b>async</b> attribute: -- -- When <b>async</b> is false, render the specified XHTML file in such a way that inner -- forms will be posted on the included view. -- -- When <b>async</b> is true, trigger an AJAX call to include the specified -- XHTML view when the page is loaded. -- -- overriding procedure Encode_Children (UI : in UIInclude; Context : in out ASF.Contexts.Faces.Faces_Context'Class); private type UIInclude is new ASF.Components.Html.UIHtmlComponent with null record; end ASF.Components.Ajax.Includes;
Add some documentation
Add some documentation
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
64837ed00dc35f3c79f3a9cc3ee158cb98dedf95
src/asf-components-widgets-likes.adb
src/asf-components-widgets-likes.adb
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; -- GNAT bug, the with clause is necessary to call Get_Global on the application. pragma Warnings (Off, "*is not referenced"); with ASF.Applications.Main; pragma Warnings (On, "*is not referenced"); with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; G_ANNOTATION_ATTR : aliased constant String := "data-annotation"; G_WIDTH_ATTR : aliased constant String := "data-width"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; FACEBOOK_ATTR_NAME : constant Unbounded_String := To_Unbounded_String ("facebook.client_id"); GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWITTER_NAME : aliased constant String := "twitter"; TWITTER_GENERATOR : aliased Twitter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;js.async=true;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId="); declare App_Id : constant Util.Beans.Objects.Object := Context.Get_Application.Get_Global (FACEBOOK_ATTR_NAME, Context.Get_ELContext.all); begin if Util.Beans.Objects.Is_Empty (App_Id) then UI.Log_Error ("The facebook client application id is empty"); UI.Log_Error ("Please, configure the {0} property in the application", To_String (FACEBOOK_ATTR_NAME)); else Writer.Queue_Script (App_Id); end if; end; Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); Style : constant String := UI.Get_Attribute ("style", Context, ""); Class : constant String := UI.Get_Attribute ("styleClass", Context, ""); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Writer.Start_Element ("div"); if Style'Length > 0 then Writer.Write_Attribute ("style", Style); end if; if Class'Length > 0 then Writer.Write_Attribute ("class", Class); end if; Generators (I).Generator.Render_Like (UI, Href, Context); Writer.End_Element ("div"); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; -- GNAT bug, the with clause is necessary to call Get_Global on the application. pragma Warnings (Off, "*is not referenced"); with ASF.Applications.Main; pragma Warnings (On, "*is not referenced"); with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; G_ANNOTATION_ATTR : aliased constant String := "data-annotation"; G_WIDTH_ATTR : aliased constant String := "data-width"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWITTER_NAME : aliased constant String := "twitter"; TWITTER_GENERATOR : aliased Twitter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;js.async=true;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId="); declare App_Id : constant String := Context.Get_Application.Get_Config (P_Facebook_App_Id.P); begin if App_Id'Length = 0 then UI.Log_Error ("The facebook client application id is empty"); UI.Log_Error ("Please, configure the '{0}' property " & "in the application", P_Facebook_App_Id.PARAM_NAME); else Writer.Queue_Script (App_Id); end if; end; Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); Style : constant String := UI.Get_Attribute ("style", Context, ""); Class : constant String := UI.Get_Attribute ("styleClass", Context, ""); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Writer.Start_Element ("div"); if Style'Length > 0 then Writer.Write_Attribute ("style", Style); end if; if Class'Length > 0 then Writer.Write_Attribute ("class", Class); end if; Generators (I).Generator.Render_Like (UI, Href, Context); Writer.End_Element ("div"); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access); end ASF.Components.Widgets.Likes;
Use the application configuration parameter to retrieve the Facebook application client ID
Use the application configuration parameter to retrieve the Facebook application client ID
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
f60b777f09d1d805e89263fb3d20099ca48dc2c9
Ada/Benchmark/src/aux_image.ads
Ada/Benchmark/src/aux_image.ads
with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; with Ada.Containers.Vectors; with Fibonacci; use Fibonacci; with Perfect_Number; use Perfect_Number; with Primes; use Primes; package Aux_Image is function Img (X : Natural) return String renames Natural'Image; function Img (X : Big_Natural) return String renames Big_Natural_Image; function Img (X : Pn_Vectors.Vector) return String; function Img (X : Prime_Vectors.Vector) return String; function Img (X : Big_Prime_Vectors.Vector) return String; private generic type T is abstract new Ada.Containers.Vectors.Vector; --type I is (<>); --type A is array (I) of T; --with function To_String (X : E) return String; function Generic_Image (X : T) return String; end Aux_Image;
with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; with Ada.Containers.Vectors; with Fibonacci; use Fibonacci; with Perfect_Number; use Perfect_Number; with Primes; use Primes; package Aux_Image is function Img (X : Natural) return String renames Natural'Image; function Img (X : Big_Natural) return String renames Big_Natural_Image; function Img (X : Pn_Vectors.Vector) return String; function Img (X : Prime_Vectors.Vector) return String; function Img (X : Big_Prime_Vectors.Vector) return String; private generic type T is private; --type I is (<>); --type A is array (I) of T; --with function To_String (X : E) return String; function Generic_Image (X : T) return String; end Aux_Image;
disable generic string generation
disable generic string generation
Ada
mit
kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground
6ac20ba0457580e6195f53cc2227eedabadee83b
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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 ASF.Requests.Tools; with ASF.Servlets.Faces; 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); Faces : aliased ASF.Servlets.Faces.Faces_Servlet; begin 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.Set_Global ("function", "Test_Load_Facelet"); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Rep : aliased ASF.Responses.Mockup.Response; Content : Unbounded_String; begin ASF.Requests.Tools.Set_Context (Req => Req, Servlet => Faces'Unchecked_Access, Response => Rep'Unchecked_Access); 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;
----------------------------------------------------------------------- -- Render Tests - Unit tests for ASF.Applications.Views -- 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.Text_IO; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Requests.Tools; with ASF.Servlets.Faces; with Ada.Directories; 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); Faces : aliased ASF.Servlets.Faces.Faces_Servlet; begin 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.Set_Global ("function", "Test_Load_Facelet"); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Rep : aliased ASF.Responses.Mockup.Response; Content : Unbounded_String; begin ASF.Requests.Tools.Set_Context (Req => Req, Servlet => Faces'Unchecked_Access, Response => Rep'Unchecked_Access); 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 warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
393c02fb9a19dc23f301c6c947e69b2e2023bd29
regtests/dlls/util-systems-dlls-tests.adb
regtests/dlls/util-systems-dlls-tests.adb
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- 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.Systems.Os; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; function Get_Test_Library return String; function Get_Test_Symbol return String; package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; function Get_Test_Library return String is begin if Util.Systems.Os.Directory_Separator = '/' then return "libcrypto.so"; else return "libz.dll"; end if; end Get_Test_Library; function Get_Test_Symbol return String is begin if Util.Systems.Os.Directory_Separator = '/' then return "inflate"; else return ""; end if; end Get_Test_Symbol; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Lib := Util.Systems.DLLs.Load (Get_Test_Library); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address; begin Lib := Util.Systems.DLLs.Load (Get_Test_Library); T.Assert (Lib /= Null_Handle, "Load operation returned null"); Sym := Util.Systems.DLLs.Get_Symbol (Lib, Get_Test_Symbol); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- 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.Systems.Os; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; function Get_Test_Library return String; function Get_Test_Symbol return String; package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; function Get_Test_Library return String is begin if Util.Systems.Os.Directory_Separator = '/' then return "libcrypto.so"; else return "libz.dll"; end if; end Get_Test_Library; function Get_Test_Symbol return String is begin if Util.Systems.Os.Directory_Separator = '/' then return "inflate"; else return "compress"; end if; end Get_Test_Symbol; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Lib := Util.Systems.DLLs.Load (Get_Test_Library); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address; begin Lib := Util.Systems.DLLs.Load (Get_Test_Library); T.Assert (Lib /= Null_Handle, "Load operation returned null"); Sym := Util.Systems.DLLs.Get_Symbol (Lib, Get_Test_Symbol); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
Fix the unit test on Get_Symbol for Windows
Fix the unit test on Get_Symbol for Windows
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7320c83c7c2040edfd277f9be073092be0078f00
src/asf-navigations.adb
src/asf-navigations.adb
----------------------------------------------------------------------- -- asf-navigations -- Navigations -- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Root; with Util.Strings; with Util.Beans.Objects; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ASF.Applications.Main; with ASF.Navigations.Render; package body ASF.Navigations is -- ------------------------------ -- Navigation Case -- ------------------------------ -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations"); -- ------------------------------ -- Check if the navigator specific condition matches the current execution context. -- ------------------------------ function Matches (Navigator : in Navigation_Case; Action : in String; Outcome : in String; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is begin -- outcome must match if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then return False; end if; -- action must match if Navigator.Action /= null and then Navigator.Action.all /= Action then return False; end if; -- condition must be true if not Navigator.Condition.Is_Constant then declare Value : constant Util.Beans.Objects.Object := Navigator.Condition.Get_Value (Context.Get_ELContext.all); begin if not Util.Beans.Objects.To_Boolean (Value) then return False; end if; end; end if; return True; end Matches; -- ------------------------------ -- Navigation Rule -- ------------------------------ -- ------------------------------ -- Search for the navigator that matches the current action, outcome and context. -- Returns the navigator or null if there was no match. -- ------------------------------ function Find_Navigation (Controller : in Rule; Action : in String; Outcome : in String; Context : in Contexts.Faces.Faces_Context'Class) return Navigation_Access is Iter : Navigator_Vector.Cursor := Controller.Navigators.First; Navigator : Navigation_Access; begin while Navigator_Vector.Has_Element (Iter) loop Navigator := Navigator_Vector.Element (Iter); -- Check if this navigator matches the action/outcome. if Navigator.Matches (Action, Outcome, Context) then return Navigator; end if; Navigator_Vector.Next (Iter); end loop; return null; end Find_Navigation; -- ------------------------------ -- Clear the navigation rules. -- ------------------------------ procedure Clear (Controller : in out Rule) is procedure Free is new Ada.Unchecked_Deallocation (Navigation_Case'Class, Navigation_Access); begin while not Controller.Navigators.Is_Empty loop declare Iter : Navigator_Vector.Cursor := Controller.Navigators.Last; Navigator : Navigation_Access := Navigator_Vector.Element (Iter); begin Free (Navigator.Outcome); Free (Navigator.Action); Free (Navigator); Controller.Navigators.Delete (Iter); end; end loop; end Clear; -- ------------------------------ -- Clear the navigation rules. -- ------------------------------ procedure Clear (Controller : in out Navigation_Rules) is procedure Free is new Ada.Unchecked_Deallocation (Rule'Class, Rule_Access); begin while not Controller.Rules.Is_Empty loop declare Iter : Rule_Map.Cursor := Controller.Rules.First; Rule : Rule_Access := Rule_Map.Element (Iter); begin Rule.Clear; Free (Rule); Controller.Rules.Delete (Iter); end; end loop; end Clear; -- ------------------------------ -- Navigation Handler -- ------------------------------ -- ------------------------------ -- Provide a default navigation rules for the view and the outcome when no application -- navigation was found. The default looks for an XHTML file in the same directory as -- the view and which has the base name defined by <b>Outcome</b>. -- ------------------------------ procedure Handle_Default_Navigation (Handler : in Navigation_Handler; View : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Pos : constant Natural := Util.Strings.Rindex (View, '/'); Root : Components.Root.UIViewRoot; View_Handler : access ASF.Applications.Views.View_Handler'Class := Handler.View_Handler; begin if View_Handler = null then View_Handler := Handler.Application.Get_View_Handler; end if; if Pos > 0 then declare Name : constant String := View (View'First .. Pos) & Outcome; begin Log.Debug ("Using default navigation from view {0} to {1}", View, Name); View_Handler.Create_View (Name, Context, Root); end; else Log.Debug ("Using default navigation from view {0} to {1}", View, View); View_Handler.Create_View (Outcome, Context, Root); end if; -- If the 'outcome' refers to a real view, use it. Otherwise keep the current view. if Components.Root.Get_Root (Root) /= null then Context.Set_View_Root (Root); end if; exception when others => Log.Debug ("No suitable navigation rule to navigate from view {0}: {1}", View, Outcome); raise; end Handle_Default_Navigation; -- ------------------------------ -- After executing an action and getting the action outcome, proceed to the navigation -- to the next page. -- ------------------------------ procedure Handle_Navigation (Handler : in Navigation_Handler; Action : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Nav_Rules : constant Navigation_Rules_Access := Handler.Rules; View : constant Components.Root.UIViewRoot := Context.Get_View_Root; Name : constant String := Components.Root.Get_View_Id (View); function Find_Navigation (View : in String) return Navigation_Access; function Find_Navigation (View : in String) return Navigation_Access is Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View)); begin if not Rule_Map.Has_Element (Pos) then return null; end if; return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context); end Find_Navigation; Navigator : Navigation_Access; begin Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome); -- Find an exact match Navigator := Find_Navigation (Name); -- Find a wildcard match if Navigator = null then declare Last : Natural := Name'Last; N : Natural; begin loop N := Util.Strings.Rindex (Name, '/', Last); exit when N = 0; Navigator := Find_Navigation (Name (Name'First .. N) & "*"); exit when Navigator /= null or N = Name'First; Last := N - 1; end loop; end; end if; -- Execute the navigation action. if Navigator /= null then Navigator.Navigate (Context); else Log.Debug ("No navigation rule found for view {0}, action {1} and outcome {2}", Name, Action, Outcome); Navigation_Handler'Class (Handler).Handle_Default_Navigation (Name, Outcome, Context); end if; end Handle_Navigation; -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Handler : in out Navigation_Handler; App : access ASF.Applications.Main.Application'Class) is begin Handler.Rules := new Navigation_Rules; Handler.Application := App; end Initialize; -- ------------------------------ -- Free the storage used by the navigation handler. -- ------------------------------ overriding procedure Finalize (Handler : in out Navigation_Handler) is procedure Free is new Ada.Unchecked_Deallocation (Navigation_Rules, Navigation_Rules_Access); begin if Handler.Rules /= null then Clear (Handler.Rules.all); Free (Handler.Rules); end if; end Finalize; -- ------------------------------ -- Add a navigation case to navigate from the view identifier by <b>From</b> -- to the result view identified by <b>To</b>. Some optional conditions are evaluated -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. -- ------------------------------ procedure Add_Navigation_Case (Handler : in out Navigation_Handler; From : in String; To : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class) is C : constant Navigation_Access := Render.Create_Render_Navigator (To, 0); begin Handler.Add_Navigation_Case (C, From, Outcome, Action, Condition, Context); end Add_Navigation_Case; -- ------------------------------ -- Add a navigation case to navigate from the view identifier by <b>From</b> -- by using the navigation rule defined by <b>Navigator</b>. -- Some optional conditions are evaluated: -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. -- ------------------------------ procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class; Navigator : in Navigation_Access; From : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class) is begin Log.Info ("Add navigation from {0} with outcome {1}", From, Outcome); if Outcome'Length > 0 then Navigator.Outcome := new String '(Outcome); end if; if Action'Length > 0 then Navigator.Action := new String '(Action); end if; if Handler.View_Handler = null then Handler.View_Handler := Handler.Application.Get_View_Handler; end if; if Condition'Length > 0 then Navigator.Condition := EL.Expressions.Create_Expression (Condition, Context); end if; Navigator.View_Handler := Handler.View_Handler; declare View : constant Unbounded_String := To_Unbounded_String (From); Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View); R : Rule_Access; begin if not Rule_Map.Has_Element (Pos) then R := new Rule; Handler.Rules.Rules.Include (Key => View, New_Item => R); else R := Rule_Map.Element (Pos); end if; R.Navigators.Append (Navigator); end; end Add_Navigation_Case; end ASF.Navigations;
----------------------------------------------------------------------- -- asf-navigations -- Navigations -- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Root; with Util.Strings; with Util.Beans.Objects; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ASF.Navigations.Render; package body ASF.Navigations is -- ------------------------------ -- Navigation Case -- ------------------------------ -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations"); -- ------------------------------ -- Check if the navigator specific condition matches the current execution context. -- ------------------------------ function Matches (Navigator : in Navigation_Case; Action : in String; Outcome : in String; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is begin -- outcome must match if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then return False; end if; -- action must match if Navigator.Action /= null and then Navigator.Action.all /= Action then return False; end if; -- condition must be true if not Navigator.Condition.Is_Constant then declare Value : constant Util.Beans.Objects.Object := Navigator.Condition.Get_Value (Context.Get_ELContext.all); begin if not Util.Beans.Objects.To_Boolean (Value) then return False; end if; end; end if; return True; end Matches; -- ------------------------------ -- Navigation Rule -- ------------------------------ -- ------------------------------ -- Search for the navigator that matches the current action, outcome and context. -- Returns the navigator or null if there was no match. -- ------------------------------ function Find_Navigation (Controller : in Rule; Action : in String; Outcome : in String; Context : in Contexts.Faces.Faces_Context'Class) return Navigation_Access is Iter : Navigator_Vector.Cursor := Controller.Navigators.First; Navigator : Navigation_Access; begin while Navigator_Vector.Has_Element (Iter) loop Navigator := Navigator_Vector.Element (Iter); -- Check if this navigator matches the action/outcome. if Navigator.Matches (Action, Outcome, Context) then return Navigator; end if; Navigator_Vector.Next (Iter); end loop; return null; end Find_Navigation; -- ------------------------------ -- Clear the navigation rules. -- ------------------------------ procedure Clear (Controller : in out Rule) is procedure Free is new Ada.Unchecked_Deallocation (Navigation_Case'Class, Navigation_Access); begin while not Controller.Navigators.Is_Empty loop declare Iter : Navigator_Vector.Cursor := Controller.Navigators.Last; Navigator : Navigation_Access := Navigator_Vector.Element (Iter); begin Free (Navigator.Outcome); Free (Navigator.Action); Free (Navigator); Controller.Navigators.Delete (Iter); end; end loop; end Clear; -- ------------------------------ -- Clear the navigation rules. -- ------------------------------ procedure Clear (Controller : in out Navigation_Rules) is procedure Free is new Ada.Unchecked_Deallocation (Rule'Class, Rule_Access); begin while not Controller.Rules.Is_Empty loop declare Iter : Rule_Map.Cursor := Controller.Rules.First; Rule : Rule_Access := Rule_Map.Element (Iter); begin Rule.Clear; Free (Rule); Controller.Rules.Delete (Iter); end; end loop; end Clear; -- ------------------------------ -- Navigation Handler -- ------------------------------ -- ------------------------------ -- Provide a default navigation rules for the view and the outcome when no application -- navigation was found. The default looks for an XHTML file in the same directory as -- the view and which has the base name defined by <b>Outcome</b>. -- ------------------------------ procedure Handle_Default_Navigation (Handler : in Navigation_Handler; View : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Pos : constant Natural := Util.Strings.Rindex (View, '/'); Root : Components.Root.UIViewRoot; begin if Pos > 0 then declare Name : constant String := View (View'First .. Pos) & Outcome; begin Log.Debug ("Using default navigation from view {0} to {1}", View, Name); Handler.View_Handler.Create_View (Name, Context, Root); end; else Log.Debug ("Using default navigation from view {0} to {1}", View, View); Handler.View_Handler.Create_View (Outcome, Context, Root); end if; -- If the 'outcome' refers to a real view, use it. Otherwise keep the current view. if Components.Root.Get_Root (Root) /= null then Context.Set_View_Root (Root); end if; exception when others => Log.Debug ("No suitable navigation rule to navigate from view {0}: {1}", View, Outcome); raise; end Handle_Default_Navigation; -- ------------------------------ -- After executing an action and getting the action outcome, proceed to the navigation -- to the next page. -- ------------------------------ procedure Handle_Navigation (Handler : in Navigation_Handler; Action : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Nav_Rules : constant Navigation_Rules_Access := Handler.Rules; View : constant Components.Root.UIViewRoot := Context.Get_View_Root; Name : constant String := Components.Root.Get_View_Id (View); function Find_Navigation (View : in String) return Navigation_Access; function Find_Navigation (View : in String) return Navigation_Access is Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View)); begin if not Rule_Map.Has_Element (Pos) then return null; end if; return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context); end Find_Navigation; Navigator : Navigation_Access; begin Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome); -- Find an exact match Navigator := Find_Navigation (Name); -- Find a wildcard match if Navigator = null then declare Last : Natural := Name'Last; N : Natural; begin loop N := Util.Strings.Rindex (Name, '/', Last); exit when N = 0; Navigator := Find_Navigation (Name (Name'First .. N) & "*"); exit when Navigator /= null or N = Name'First; Last := N - 1; end loop; end; end if; -- Execute the navigation action. if Navigator /= null then Navigator.Navigate (Context); else Log.Debug ("No navigation rule found for view {0}, action {1} and outcome {2}", Name, Action, Outcome); Navigation_Handler'Class (Handler).Handle_Default_Navigation (Name, Outcome, Context); end if; end Handle_Navigation; -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Handler : in out Navigation_Handler; Views : access ASF.Applications.Views.View_Handler'Class) is begin Handler.Rules := new Navigation_Rules; Handler.View_Handler := Views; end Initialize; -- ------------------------------ -- Free the storage used by the navigation handler. -- ------------------------------ overriding procedure Finalize (Handler : in out Navigation_Handler) is procedure Free is new Ada.Unchecked_Deallocation (Navigation_Rules, Navigation_Rules_Access); begin if Handler.Rules /= null then Clear (Handler.Rules.all); Free (Handler.Rules); end if; end Finalize; -- ------------------------------ -- Add a navigation case to navigate from the view identifier by <b>From</b> -- to the result view identified by <b>To</b>. Some optional conditions are evaluated -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. -- ------------------------------ procedure Add_Navigation_Case (Handler : in out Navigation_Handler; From : in String; To : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class) is C : constant Navigation_Access := Render.Create_Render_Navigator (To, 0); begin Handler.Add_Navigation_Case (C, From, Outcome, Action, Condition, Context); end Add_Navigation_Case; -- ------------------------------ -- Add a navigation case to navigate from the view identifier by <b>From</b> -- by using the navigation rule defined by <b>Navigator</b>. -- Some optional conditions are evaluated: -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. -- ------------------------------ procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class; Navigator : in Navigation_Access; From : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class) is begin Log.Info ("Add navigation from {0} with outcome {1}", From, Outcome); if Outcome'Length > 0 then Navigator.Outcome := new String '(Outcome); end if; if Action'Length > 0 then Navigator.Action := new String '(Action); end if; -- if Handler.View_Handler = null then -- Handler.View_Handler := Handler.Application.Get_View_Handler; -- end if; if Condition'Length > 0 then Navigator.Condition := EL.Expressions.Create_Expression (Condition, Context); end if; Navigator.View_Handler := Handler.View_Handler; declare View : constant Unbounded_String := To_Unbounded_String (From); Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View); R : Rule_Access; begin if not Rule_Map.Has_Element (Pos) then R := new Rule; Handler.Rules.Rules.Include (Key => View, New_Item => R); else R := Rule_Map.Element (Pos); end if; R.Navigators.Append (Navigator); end; end Add_Navigation_Case; end ASF.Navigations;
Use ASF.Applications.Views.View_Handler'Class to avoid using a 'limited with' clause
Use ASF.Applications.Views.View_Handler'Class to avoid using a 'limited with' clause
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f9b887142ae52c9c8d79d09208e95650490f739b
regtests/ado-drivers-tests.adb
regtests/ado-drivers-tests.adb
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; 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.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); end Add_Tests; -- ------------------------------ -- 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); 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; end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; 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); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is 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); 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; end ADO.Drivers.Tests;
Implement Test_Initialize procedure to check the Initialize procedure
Implement Test_Initialize procedure to check the Initialize procedure
Ada
apache-2.0
stcarrez/ada-ado
9a4e54f16ea899fe01d991889a80d4884d2ab38d
samples/beans/users.adb
samples/beans/users.adb
----------------------------------------------------------------------- -- users - Gives access to the OpenID principal through an Ada bean -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Contexts.Faces; with ASF.Contexts.Flash; with ASF.Sessions; with ASF.Principals; with ASF.Cookies; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Factory; with GNAT.MD5; with Security.Openid; with ASF.Security.Filters; with Util.Strings.Transforms; package body Users is use Ada.Strings.Unbounded; use Security.Openid; use type ASF.Principals.Principal_Access; use type ASF.Contexts.Faces.Faces_Context_Access; -- ------------------------------ -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) -- ------------------------------ function Get_Gravatar_Link (Email : in String) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- Get the user information identified by the given name. -- ------------------------------ function Get_Value (From : in User_Info; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session; P : ASF.Principals.Principal_Access := null; U : Security.Openid.Principal_Access := null; begin if F /= null then S := F.Get_Session; if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.Openid.Principal'Class (P.all)'Access; end if; end if; end if; if Name = "authenticated" then return Util.Beans.Objects.To_Object (U /= null); end if; if U = null then return Util.Beans.Objects.Null_Object; end if; if Name = "email" then return Util.Beans.Objects.To_Object (U.Get_Email); end if; if Name = "language" then return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication)); end if; if Name = "first_name" then return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication)); end if; if Name = "last_name" then return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication)); end if; if Name = "full_name" then return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication)); end if; if Name = "id" then return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication)); end if; if Name = "country" then return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication)); end if; if Name = "sessionId" then return Util.Beans.Objects.To_Object (S.Get_Id); end if; if Name = "gravatar" then return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email)); end if; return Util.Beans.Objects.To_Object (U.Get_Name); end Get_Value; -- ------------------------------ -- Helper to send a remove cookie in the current response -- ------------------------------ procedure Remove_Cookie (Name : in String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end Remove_Cookie; -- ------------------------------ -- Logout by dropping the user session. -- ------------------------------ procedure Logout (From : in out User_Info; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session := F.Get_Session; P : ASF.Principals.Principal_Access := null; U : Security.Openid.Principal_Access := null; begin if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.Openid.Principal'Class (P.all)'Access; end if; S.Invalidate; end if; if U /= null then F.Get_Flash.Set_Keep_Messages (True); ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message", Get_Full_Name (U.Get_Authentication)); end if; Remove_Cookie (ASF.Security.Filters.SID_COOKIE); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success"); end Logout; package Logout_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info, Method => Logout, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Logout_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in User_Info) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; end Users;
----------------------------------------------------------------------- -- users - Gives access to the OpenID principal through an Ada bean -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Contexts.Faces; with ASF.Contexts.Flash; with ASF.Sessions; with ASF.Principals; with ASF.Cookies; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Factory; with GNAT.MD5; with Security.OpenID; with ASF.Security.Filters; with Util.Strings.Transforms; package body Users is use Ada.Strings.Unbounded; use Security.OpenID; use type ASF.Principals.Principal_Access; use type ASF.Contexts.Faces.Faces_Context_Access; procedure Remove_Cookie (Name : in String); -- ------------------------------ -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) -- ------------------------------ function Get_Gravatar_Link (Email : in String) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin return "http://www.gravatar.com/avatar/" & C; end Get_Gravatar_Link; -- ------------------------------ -- Get the user information identified by the given name. -- ------------------------------ function Get_Value (From : in User_Info; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session; P : ASF.Principals.Principal_Access := null; U : Security.OpenID.Principal_Access := null; begin if F /= null then S := F.Get_Session; if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.OpenID.Principal'Class (P.all)'Access; end if; end if; end if; if Name = "authenticated" then return Util.Beans.Objects.To_Object (U /= null); end if; if U = null then return Util.Beans.Objects.Null_Object; end if; if Name = "email" then return Util.Beans.Objects.To_Object (U.Get_Email); end if; if Name = "language" then return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication)); end if; if Name = "first_name" then return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication)); end if; if Name = "last_name" then return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication)); end if; if Name = "full_name" then return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication)); end if; if Name = "id" then return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication)); end if; if Name = "country" then return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication)); end if; if Name = "sessionId" then return Util.Beans.Objects.To_Object (S.Get_Id); end if; if Name = "gravatar" then return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email)); end if; return Util.Beans.Objects.To_Object (U.Get_Name); end Get_Value; -- ------------------------------ -- Helper to send a remove cookie in the current response -- ------------------------------ procedure Remove_Cookie (Name : in String) is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, ""); begin ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 0); Ctx.Get_Response.Add_Cookie (Cookie => C); end Remove_Cookie; -- ------------------------------ -- Logout by dropping the user session. -- ------------------------------ procedure Logout (From : in out User_Info; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (From); F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; S : ASF.Sessions.Session := F.Get_Session; P : ASF.Principals.Principal_Access := null; U : Security.OpenID.Principal_Access := null; begin if S.Is_Valid then P := S.Get_Principal; if P /= null then U := Security.OpenID.Principal'Class (P.all)'Access; end if; S.Invalidate; end if; if U /= null then F.Get_Flash.Set_Keep_Messages (True); ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message", Get_Full_Name (U.Get_Authentication)); end if; Remove_Cookie (ASF.Security.Filters.SID_COOKIE); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success"); end Logout; package Logout_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info, Method => Logout, Name => "logout"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Logout_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in User_Info) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; end Users;
Fix some compilation warnings
Fix some compilation warnings
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
e3d45c608a1d88143f0b7b76b4584183c0c17ce5
orka_transforms/src/orka-transforms-simd_matrices.adb
orka_transforms/src/orka-transforms-simd_matrices.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Matrices is package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function Diagonal (Elements : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin for Index in Elements'Range loop Result (Index) (Index) := Elements (Index); end loop; return Result; end Diagonal; function Main_Diagonal (Matrix : Matrix_Type) return Vector_Type is (Matrix (X) (X), Matrix (Y) (Y), Matrix (Z) (Z), Matrix (W) (W)); function Trace (Matrix : Matrix_Type) return Element_Type is (Vectors.Sum (Main_Diagonal (Matrix))); function "*" (Left : Vector_Type; Right : Matrix_Type) return Vector_Type is Result : Vector_Type; begin for Column in Right'Range loop Result (Column) := Vectors.Dot (Left, Right (Column)); end loop; return Result; end "*"; function Outer (Left, Right : Vector_Type) return Matrix_Type is use Vectors; Result : Matrix_Type; begin for Index in Right'Range loop Result (Index) := Right (Index) * Left; end loop; return Result; end Outer; ---------------------------------------------------------------------------- function T (Offset : Vectors.Point) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Vector_Type (Offset); return Result; end T; function T (Offset : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Offset; Result (W) (W) := 1.0; return Result; end T; function Rx (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (Y) := (0.0, CA, SA, 0.0); Result (Z) := (0.0, -SA, CA, 0.0); return Result; end Rx; function Ry (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, 0.0, -SA, 0.0); Result (Z) := (SA, 0.0, CA, 0.0); return Result; end Ry; function Rz (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, SA, 0.0, 0.0); Result (Y) := (-SA, CA, 0.0, 0.0); return Result; end Rz; function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); MCA : constant Element_Type := 1.0 - CA; MCARXY : constant Element_Type := MCA * Axis (X) * Axis (Y); MCARXZ : constant Element_Type := MCA * Axis (X) * Axis (Z); MCARYZ : constant Element_Type := MCA * Axis (Y) * Axis (Z); RXSA : constant Element_Type := Axis (X) * SA; RYSA : constant Element_Type := Axis (Y) * SA; RZSA : constant Element_Type := Axis (Z) * SA; R11 : constant Element_Type := CA + MCA * Axis (X)**2; R12 : constant Element_Type := MCARXY + RZSA; R13 : constant Element_Type := MCARXZ - RYSA; R21 : constant Element_Type := MCARXY - RZSA; R22 : constant Element_Type := CA + MCA * Axis (Y)**2; R23 : constant Element_Type := MCARYZ + RXSA; R31 : constant Element_Type := MCARXZ + RYSA; R32 : constant Element_Type := MCARYZ - RXSA; R33 : constant Element_Type := CA + MCA * Axis (Z)**2; Result : Matrix_Type; begin Result (X) := (R11, R12, R13, 0.0); Result (Y) := (R21, R22, R23, 0.0); Result (Z) := (R31, R32, R33, 0.0); Result (W) := (0.0, 0.0, 0.0, 1.0); return Result; end R; function R (Quaternion : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; Q_X : constant Element_Type := Quaternion (X); Q_Y : constant Element_Type := Quaternion (Y); Q_Z : constant Element_Type := Quaternion (Z); Q_W : constant Element_Type := Quaternion (W); S : constant := 2.0; -- S = 2 / Norm (Quaternion) begin Result (X) (X) := 1.0 - S * (Q_Y * Q_Y + Q_Z * Q_Z); Result (X) (Y) := S * (Q_X * Q_Y - Q_Z * Q_W); Result (X) (Z) := S * (Q_X * Q_Z + Q_Y * Q_W); Result (Y) (X) := S * (Q_X * Q_Y + Q_Z * Q_W); Result (Y) (Y) := 1.0 - S * (Q_X * Q_X + Q_Z * Q_Z); Result (Y) (Z) := S * (Q_Y * Q_Z - Q_X * Q_W); Result (Z) (X) := S * (Q_X * Q_Z - Q_Y * Q_W); Result (Z) (Y) := S * (Q_Y * Q_Z + Q_X * Q_W); Result (Z) (Z) := 1.0 - S * (Q_X * Q_X + Q_Y * Q_Y); return Result; end R; function S (Factors : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := Factors (X); Result (Y) (Y) := Factors (Y); Result (Z) (Z) := Factors (Z); return Result; end S; ---------------------------------------------------------------------------- function FOV (Width, Distance : Element_Type) return Element_Type is (2.0 * EF.Arctan (Width / (2.0 * Distance))); function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Z_Far / (Z_Near - Z_Far); Result (W) (Z) := (Z_Near * Z_Far) / (Z_Near - Z_Far); Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Finite_Perspective; function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Element_Type (-1.0); Result (W) (Z) := -Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective; function Infinite_Perspective_Reversed_Z (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [1, 0] instead of [-1 , 1] Result (Z) (Z) := Element_Type (0.0); Result (W) (Z) := Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective_Reversed_Z; function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := 2.0 / X_Mag; Result (Y) (Y) := 2.0 / Y_Mag; -- Depth normalized to [0, 1] instead of [-1, 1] Result (Z) (Z) := -1.0 / (Z_Far - Z_Near); Result (W) (Z) := -Z_Near / (Z_Far - Z_Near); return Result; end Orthographic; end Orka.Transforms.SIMD_Matrices;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Matrices is package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type); function Diagonal (Elements : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin for Index in Elements'Range loop Result (Index) (Index) := Elements (Index); end loop; return Result; end Diagonal; function Main_Diagonal (Matrix : Matrix_Type) return Vector_Type is (Matrix (X) (X), Matrix (Y) (Y), Matrix (Z) (Z), Matrix (W) (W)); function Trace (Matrix : Matrix_Type) return Element_Type is (Vectors.Sum (Main_Diagonal (Matrix))); function "*" (Left : Vector_Type; Right : Matrix_Type) return Vector_Type is Result : Vector_Type; begin for Column in Right'Range loop Result (Column) := Vectors.Dot (Left, Right (Column)); end loop; return Result; end "*"; function Outer (Left, Right : Vector_Type) return Matrix_Type is use Vectors; Result : Matrix_Type; begin for Index in Right'Range loop Result (Index) := Right (Index) * Left; end loop; return Result; end Outer; ---------------------------------------------------------------------------- function T (Offset : Vectors.Point) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Vector_Type (Offset); return Result; end T; function T (Offset : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (W) := Offset; Result (W) (W) := 1.0; return Result; end T; function Rx (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (Y) := (0.0, CA, SA, 0.0); Result (Z) := (0.0, -SA, CA, 0.0); return Result; end Rx; function Ry (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, 0.0, -SA, 0.0); Result (Z) := (SA, 0.0, CA, 0.0); return Result; end Ry; function Rz (Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); Result : Matrix_Type := Identity_Matrix; begin Result (X) := (CA, SA, 0.0, 0.0); Result (Y) := (-SA, CA, 0.0, 0.0); return Result; end Rz; function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type is CA : constant Element_Type := EF.Cos (Angle); SA : constant Element_Type := EF.Sin (Angle); MCA : constant Element_Type := 1.0 - CA; MCARXY : constant Element_Type := MCA * Axis (X) * Axis (Y); MCARXZ : constant Element_Type := MCA * Axis (X) * Axis (Z); MCARYZ : constant Element_Type := MCA * Axis (Y) * Axis (Z); RXSA : constant Element_Type := Axis (X) * SA; RYSA : constant Element_Type := Axis (Y) * SA; RZSA : constant Element_Type := Axis (Z) * SA; R11 : constant Element_Type := CA + MCA * Axis (X)**2; R12 : constant Element_Type := MCARXY + RZSA; R13 : constant Element_Type := MCARXZ - RYSA; R21 : constant Element_Type := MCARXY - RZSA; R22 : constant Element_Type := CA + MCA * Axis (Y)**2; R23 : constant Element_Type := MCARYZ + RXSA; R31 : constant Element_Type := MCARXZ + RYSA; R32 : constant Element_Type := MCARYZ - RXSA; R33 : constant Element_Type := CA + MCA * Axis (Z)**2; Result : Matrix_Type; begin Result (X) := (R11, R12, R13, 0.0); Result (Y) := (R21, R22, R23, 0.0); Result (Z) := (R31, R32, R33, 0.0); Result (W) := (0.0, 0.0, 0.0, 1.0); return Result; end R; function R (Quaternion : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; Q_X : constant Element_Type := Quaternion (X); Q_Y : constant Element_Type := Quaternion (Y); Q_Z : constant Element_Type := Quaternion (Z); Q_W : constant Element_Type := Quaternion (W); S : constant := 2.0; -- S = 2 / Norm (Quaternion) begin Result (X) (X) := 1.0 - S * (Q_Y * Q_Y + Q_Z * Q_Z); Result (X) (Y) := S * (Q_X * Q_Y + Q_Z * Q_W); Result (X) (Z) := S * (Q_X * Q_Z - Q_Y * Q_W); Result (Y) (X) := S * (Q_X * Q_Y - Q_Z * Q_W); Result (Y) (Y) := 1.0 - S * (Q_X * Q_X + Q_Z * Q_Z); Result (Y) (Z) := S * (Q_Y * Q_Z + Q_X * Q_W); Result (Z) (X) := S * (Q_X * Q_Z + Q_Y * Q_W); Result (Z) (Y) := S * (Q_Y * Q_Z - Q_X * Q_W); Result (Z) (Z) := 1.0 - S * (Q_X * Q_X + Q_Y * Q_Y); return Result; end R; function S (Factors : Vector_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := Factors (X); Result (Y) (Y) := Factors (Y); Result (Z) (Z) := Factors (Z); return Result; end S; ---------------------------------------------------------------------------- function FOV (Width, Distance : Element_Type) return Element_Type is (2.0 * EF.Arctan (Width / (2.0 * Distance))); function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Z_Far / (Z_Near - Z_Far); Result (W) (Z) := (Z_Near * Z_Far) / (Z_Near - Z_Far); Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Finite_Perspective; function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [0, 1] instead of [-1 , 1] Result (Z) (Z) := Element_Type (-1.0); Result (W) (Z) := -Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective; function Infinite_Perspective_Reversed_Z (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV); Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := F / Aspect; Result (Y) (Y) := F; -- Depth normalized to [1, 0] instead of [-1 , 1] Result (Z) (Z) := Element_Type (0.0); Result (W) (Z) := Z_Near; Result (Z) (W) := Element_Type (-1.0); Result (W) (W) := Element_Type (0.0); return Result; end Infinite_Perspective_Reversed_Z; function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type is Result : Matrix_Type := Identity_Matrix; begin Result (X) (X) := 2.0 / X_Mag; Result (Y) (Y) := 2.0 / Y_Mag; -- Depth normalized to [0, 1] instead of [-1, 1] Result (Z) (Z) := -1.0 / (Z_Far - Z_Near); Result (W) (Z) := -Z_Near / (Z_Far - Z_Near); return Result; end Orthographic; end Orka.Transforms.SIMD_Matrices;
Fix positions of elements in function R
transforms: Fix positions of elements in function R The type Matrix_Type uses column-major order. Fix the positions so that it is equal to Equation 4.42 from chapter 4.3 Quaternions from [1]. [1] "Real-Time Rendering" (third edition, 2008) Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
add8747cf365a6da817e483d3509faeb1fdb1747
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply, "Blog post page is invalid" ); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("post-format", "dotclear"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "dotclear"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "POST_PUBLISHED"); Request.Set_Parameter ("format", "dotclear"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Publish_Date; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply, "Blog post page is invalid" ); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("post-format", "dotclear"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "dotclear"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "dotclear"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Publish_Date; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
Fix name of format parameter for the unit test
Fix name of format parameter for the unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
823db945594c279bc30b0273b74609f31c1e6957
awa/plugins/awa-comments/src/awa-comments-beans.adb
awa/plugins/awa-comments/src/awa-comments-beans.adb
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "message" then From.Set_Message (Util.Beans.Objects.To_String (Value)); elsif Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "status" then From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- Save the comment. overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "message" then From.Set_Message (Util.Beans.Objects.To_String (Value)); elsif Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "status" then From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- ------------------------------ -- Save the comment. -- ------------------------------ overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Update_Comment (Permission => To_String (Bean.Permission), Comment => Bean); end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
Implement the Save action bean by using the Update_Comment operation
Implement the Save action bean by using the Update_Comment operation
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
cf8d8adf3744f0b0bf0988edabc4b716dba27dfb
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
Update according to the UML model
Update according to the UML model
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
687a336757bfa003c76103d45078af7997657c34
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 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 integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val); 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) is begin Console_Type'Class (Console).Print_Field (Field, Ada.Strings.Unbounded.To_String (Value)); end Print_Field; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- 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 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) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val); 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) is begin Console_Type'Class (Console).Print_Field (Field, Ada.Strings.Unbounded.To_String (Value)); end Print_Field; end MAT.Consoles;
Implement the Print_Duration operation
Implement the Print_Duration operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
02ef160fcad6f9356cca46edc88e6131c6ce1efe
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Blogs.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Counters.Modules.Tests; with AWA.Workspaces.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; -- with ASF.Server.Web; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Workspaces.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); Application.Start; -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- Application.Add_Converter (Name => "dateConverter", -- Converter => Date_Converter'Access); -- Application.Add_Converter (Name => "smartDateConverter", -- Converter => Rel_Date_Converter'Access); -- -- WS.Register_Application ("/asfunit", Application.all'Access); -- -- WS.Start; -- delay 6000.0; -- end; -- end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Blogs.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Counters.Modules.Tests; with AWA.Workspaces.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; -- with ASF.Server.Web; with Servlet.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Workspaces.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); Application.Start; -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- Application.Add_Converter (Name => "dateConverter", -- Converter => Date_Converter'Access); -- Application.Add_Converter (Name => "smartDateConverter", -- Converter => Rel_Date_Converter'Access); -- -- WS.Register_Application ("/asfunit", Application.all'Access); -- -- WS.Start; -- delay 6000.0; -- end; -- end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Update to use the Servlet package instead of ASF.Servlet
Update to use the Servlet package instead of ASF.Servlet
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e6b3496b581621de39cb18f244e74829734cc3bb
src/asf-contexts-writer.ads
src/asf-contexts-writer.ads
----------------------------------------------------------------------- -- writer -- Response stream writer -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ASF.Contexts.Writer</b> defines the response writer to -- write the rendered result to the response stream. The <b>IOWriter</b> -- interface defines the procedure for writing the buffer to the output -- stream. The <b>Response_Writer</b> is the main type that provides -- various methods for writing the content. -- -- The result stream is encoded according to the encoding type. -- with Unicode.Encodings; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with EL.Objects; with Util.Beans.Objects; with Util.Strings.Builders; with ASF.Streams; package ASF.Contexts.Writer is use Ada.Strings.Unbounded; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- IO Writer -- ------------------------------ type IOWriter is limited interface; procedure Write (Stream : in out IOWriter; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- ------------------------------ -- Response Writer -- ------------------------------ type Response_Writer is new ASF.Streams.Print_Stream with private; type Response_Writer_Access is access all Response_Writer'Class; -- Backward compatibility subtype ResponseWriter is Response_Writer; pragma Obsolescent (Entity => ResponseWriter); subtype ResponseWriter_Access is Response_Writer_Access; pragma Obsolescent (Entity => ResponseWriter_Access); -- Initialize the response stream for the given content type and -- encoding. An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Response_Writer; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream); -- Get the content type. function Get_Content_Type (Stream : in Response_Writer) return String; -- Get the character encoding. function Get_Encoding (Stream : in Response_Writer) return String; -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Response_Writer'Class); -- Start an XML element with the given name. procedure Start_Element (Stream : in out Response_Writer; Name : in String); -- Start an optional XML element with the given name. -- The element is written only if it has at least one attribute. -- The optional XML element must not contain other XML entities. procedure Start_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Closes an XML element of the given name. procedure End_Element (Stream : in out Response_Writer; Name : in String); -- Closes an optional XML element of the given name. -- The ending tag is written only if the start tag was written. procedure End_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Element (Stream : in out Response_Writer; Name : in String; Content : in String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Wide_Wide_String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in EL.Objects.Object); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Wide_Wide_String); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_Wide_Wide_String); -- Write a text escaping any character as necessary. procedure Write_Text (Stream : in out Response_Writer; Text : in String); procedure Write_Text (Stream : in out Response_Writer; Text : in Unbounded_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Wide_Wide_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Unbounded_Wide_Wide_String); procedure Write_Text (Stream : in out Response_Writer; Value : in EL.Objects.Object); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Char (Stream : in out Response_Writer; Char : in Character); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Wide_Char (Stream : in out Response_Writer; Char : in Wide_Wide_Character); -- Write a string on the stream. procedure Write (Stream : in out Response_Writer; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in String); -- Write a raw wide string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write a raw wide string on the stream. procedure Write_Wide_Raw (Stream : in out Response_Writer; Item : in Wide_Wide_String); -- ------------------------------ -- Javascript Support -- ------------------------------ -- To optimize the execution of Javascript page code, ASF components can queue some -- javascript code and have it merged and executed in a single <script> command. -- Write the java scripts that have been queued by <b>Queue_Script</b> procedure Write_Scripts (Stream : in out Response_Writer); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in String); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in Ada.Strings.Unbounded.Unbounded_String); -- Append the <b>Value</b> to the javascript buffer queue. The value is escaped according -- to Javascript escape rules. procedure Queue_Script (Stream : in out Response_Writer; Value : in Util.Beans.Objects.Object); -- Append a <b>script</b> include command to include the Javascript file at the given URL. -- The include scripts are flushed by <b>Flush</b> or <b>Write_Scripts</b>. procedure Queue_Include_Script (Stream : in out Response_Writer; URL : in String); -- Flush the response. -- Before flusing the response, the javascript are also flushed -- by calling <b>Write_Scripts</b>. overriding procedure Flush (Stream : in out Response_Writer); private use Ada.Streams; -- Flush the response stream and release the buffer. overriding procedure Finalize (Object : in out Response_Writer); type Buffer_Access is access Ada.Streams.Stream_Element_Array; type Response_Writer is new ASF.Streams.Print_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; -- The encoding scheme. Encoding : Unicode.Encodings.Unicode_Encoding; -- The content type. Content_Type : Unbounded_String; -- The javascript that has been queued by <b>Queue_Script</b>. Script_Queue : Unbounded_String; -- Util.Strings.Builders.Builder (256); -- The javascript files that must be included at the end of the file. -- This javascript part is written before the Javascript that was queued. Include_Queue : Util.Strings.Builders.Builder (256); -- An optional element to write in the stream. Optional_Element : String (1 .. 32); Optional_Element_Size : Natural := 0; Optional_Element_Written : Boolean := False; end record; end ASF.Contexts.Writer;
----------------------------------------------------------------------- -- writer -- Response stream writer -- Copyright (C) 2009, 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. ----------------------------------------------------------------------- -- The <b>ASF.Contexts.Writer</b> defines the response writer to -- write the rendered result to the response stream. The <b>IOWriter</b> -- interface defines the procedure for writing the buffer to the output -- stream. The <b>Response_Writer</b> is the main type that provides -- various methods for writing the content. -- -- The result stream is encoded according to the encoding type. -- with Unicode.Encodings; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with EL.Objects; with Util.Beans.Objects; with Util.Strings.Builders; with ASF.Streams; package ASF.Contexts.Writer is use Ada.Strings.Unbounded; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- IO Writer -- ------------------------------ type IOWriter is limited interface; procedure Write (Stream : in out IOWriter; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- ------------------------------ -- Response Writer -- ------------------------------ type Response_Writer is new ASF.Streams.Print_Stream with private; type Response_Writer_Access is access all Response_Writer'Class; -- Backward compatibility subtype ResponseWriter is Response_Writer; pragma Obsolescent (Entity => ResponseWriter); subtype ResponseWriter_Access is Response_Writer_Access; pragma Obsolescent (Entity => ResponseWriter_Access); -- Initialize the response stream for the given content type and -- encoding. An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Response_Writer; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream); -- Get the content type. function Get_Content_Type (Stream : in Response_Writer) return String; -- Get the character encoding. function Get_Encoding (Stream : in Response_Writer) return String; -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Response_Writer'Class); -- Start an XML element with the given name. procedure Start_Element (Stream : in out Response_Writer; Name : in String); -- Start an optional XML element with the given name. -- The element is written only if it has at least one attribute. -- The optional XML element must not contain other XML entities. procedure Start_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Closes an XML element of the given name. procedure End_Element (Stream : in out Response_Writer; Name : in String); -- Closes an optional XML element of the given name. -- The ending tag is written only if the start tag was written. procedure End_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Element (Stream : in out Response_Writer; Name : in String; Content : in String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Wide_Wide_String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in EL.Objects.Object); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Wide_Wide_String); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_Wide_Wide_String); -- Write a text escaping any character as necessary. procedure Write_Text (Stream : in out Response_Writer; Text : in String); procedure Write_Text (Stream : in out Response_Writer; Text : in Unbounded_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Wide_Wide_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Unbounded_Wide_Wide_String); procedure Write_Text (Stream : in out Response_Writer; Value : in EL.Objects.Object); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Char (Stream : in out Response_Writer; Char : in Character); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Wide_Char (Stream : in out Response_Writer; Char : in Wide_Wide_Character); -- Write a string on the stream. procedure Write (Stream : in out Response_Writer; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in String); -- Write a raw wide string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write a raw wide string on the stream. procedure Write_Wide_Raw (Stream : in out Response_Writer; Item : in Wide_Wide_String); -- ------------------------------ -- Javascript Support -- ------------------------------ -- To optimize the execution of Javascript page code, ASF components can queue some -- javascript code and have it merged and executed in a single <script> command. -- Write the java scripts that have been queued by <b>Queue_Script</b> procedure Write_Scripts (Stream : in out Response_Writer); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in String); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in Ada.Strings.Unbounded.Unbounded_String); -- Append the <b>Value</b> to the javascript buffer queue. The value is escaped according -- to Javascript escape rules. procedure Queue_Script (Stream : in out Response_Writer; Value : in Util.Beans.Objects.Object); -- Append a <b>script</b> include command to include the Javascript file at the given URL. -- The include scripts are flushed by <b>Flush</b> or <b>Write_Scripts</b>. procedure Queue_Include_Script (Stream : in out Response_Writer; URL : in String; Async : in Boolean := False); -- Flush the response. -- Before flusing the response, the javascript are also flushed -- by calling <b>Write_Scripts</b>. overriding procedure Flush (Stream : in out Response_Writer); private use Ada.Streams; -- Flush the response stream and release the buffer. overriding procedure Finalize (Object : in out Response_Writer); type Buffer_Access is access Ada.Streams.Stream_Element_Array; type Response_Writer is new ASF.Streams.Print_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; -- The encoding scheme. Encoding : Unicode.Encodings.Unicode_Encoding; -- The content type. Content_Type : Unbounded_String; -- The javascript that has been queued by <b>Queue_Script</b>. Script_Queue : Unbounded_String; -- Util.Strings.Builders.Builder (256); -- The javascript files that must be included at the end of the file. -- This javascript part is written before the Javascript that was queued. Include_Queue : Util.Strings.Builders.Builder (256); -- An optional element to write in the stream. Optional_Element : String (1 .. 32); Optional_Element_Size : Natural := 0; Optional_Element_Written : Boolean := False; end record; end ASF.Contexts.Writer;
Add the Async parameter to the Queue_Include_Script procedure
Add the Async parameter to the Queue_Include_Script procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
a1a20c3a9ef0397b774ada3540848a800dd5e872
orka_egl/src/egl-api.ads
orka_egl/src/egl-api.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 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 Interfaces.C.Strings; with System; with EGL.Errors; with EGL.Loading; with EGL.Objects.Contexts; with EGL.Objects.Displays; with EGL.Objects.Devices; private package EGL.API is pragma Preelaborate; pragma Linker_Options ("-lEGL"); function Get_Proc_Address (Name : C.char_array) return System.Address with Import, Convention => C, External_Name => "eglGetProcAddress"; function Get_Error return Errors.Error_Code with Import, Convention => C, External_Name => "eglGetError"; package Debug_Message_Control is new Loading.Function_With_2_Params ("eglDebugMessageControlKHR", System.Address, Attribute_Array, Errors.Error_Code); ----------------------------------------------------------------------------- -- Displays -- ----------------------------------------------------------------------------- package Get_Platform_Display is new Loading.Function_With_3_Params ("eglGetPlatformDisplayEXT", Objects.Displays.Platform_Kind, Void_Ptr, Int_Array, ID_Type); function Initialize_Display (Display : ID_Type; Major, Minor : out Int) return Bool with Import, Convention => C, External_Name => "eglInitialize"; function Terminate_Display (Display : ID_Type) return Bool with Import, Convention => C, External_Name => "eglTerminate"; function Query_String (No_Display : ID_Type; Name : Display_Query_Param) return C.Strings.chars_ptr with Import, Convention => C, External_Name => "eglQueryString"; -- Return a zero-terminated string with the properties of the EGL -- client or the EGL display, or null if an error occurred ----------------------------------------------------------------------------- -- Contexts -- ----------------------------------------------------------------------------- function Bind_API (API : Objects.Contexts.Client_API) return Bool with Import, Convention => C, External_Name => "eglBindAPI"; function Create_Context (Display : ID_Type; Config : ID_Type; Share : ID_Type; Attributes : Int_Array) return ID_Type with Import, Convention => C, External_Name => "eglCreateContext"; function Destroy_Context (Display : ID_Type; Context : ID_Type) return Bool with Import, Convention => C, External_Name => "eglDestroyContext"; function Make_Current (Display : ID_Type; Draw : ID_Type; Read : ID_Type; Context : ID_Type) return Bool with Import, Convention => C, External_Name => "eglMakeCurrent"; ----------------------------------------------------------------------------- -- Surfaces -- ----------------------------------------------------------------------------- -- eglSurfaceAttrib function Query_Surface (Display : ID_Type; Surface : ID_Type; Attribute : Surface_Query_Param; Value : out Int) return Bool with Import, Convention => C, External_Name => "eglQuerySurface"; function Query_Context (Display : ID_Type; Context : ID_Type; Attribute : Context_Query_Param; Value : out Objects.Contexts.Buffer_Kind) return Bool with Import, Convention => C, External_Name => "eglQueryContext"; function Get_Current_Context return ID_Type with Import, Convention => C, External_Name => "eglGetCurrentContext"; function Get_Config_Attrib (Display : ID_Type; Config : ID_Type; Attribute : Int; Value : out Int) return Bool with Import, Convention => C, External_Name => "eglGetConfigAttrib"; function Choose_Config (Display : ID_Type; Attributes : Int_Array; Configs : out ID_Array; Max_Configs : Int; Length : out Int) return Bool with Import, Convention => C, External_Name => "eglChooseConfig"; package Create_Platform_Window_Surface is new Loading.Function_With_4_Params ("eglCreatePlatformWindowSurfaceEXT", ID_Type, ID_Type, Native_Window_Ptr, Int_Array, ID_Type); function Destroy_Surface (Display : ID_Type; Surface : ID_Type) return Bool with Import, Convention => C, External_Name => "eglDestroySurface"; function Swap_Buffers (Display : ID_Type; Surface : ID_Type) return Bool with Import, Convention => C, External_Name => "eglSwapBuffers"; function Swap_Interval (Display : ID_Type; Interval : Int) return Bool with Import, Convention => C, External_Name => "eglSwapInterval"; ----------------------------------------------------------------------------- -- Devices -- ----------------------------------------------------------------------------- package Query_Device_String is new Loading.Function_With_2_Params ("eglQueryDeviceStringEXT", ID_Type, Device_Query_Param, C.Strings.chars_ptr); -- Return the DRM name of a device or a list of device extensions package Query_Display_Attrib is new Loading.Getter_With_3_Params ("eglQueryDisplayAttribEXT", ID_Type, Int, ID_Type, Bool); -- Return the device of a display package Query_Devices is new Loading.Array_Getter_With_3_Params ("eglQueryDevicesEXT", Int, ID_Type, ID_Array, Int, Bool); end EGL.API;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 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 Interfaces.C.Strings; with System; with EGL.Errors; with EGL.Loading; with EGL.Objects.Contexts; with EGL.Objects.Displays; private package EGL.API is pragma Preelaborate; pragma Linker_Options ("-lEGL"); function Get_Proc_Address (Name : C.char_array) return System.Address with Import, Convention => C, External_Name => "eglGetProcAddress"; function Get_Error return Errors.Error_Code with Import, Convention => C, External_Name => "eglGetError"; package Debug_Message_Control is new Loading.Function_With_2_Params ("eglDebugMessageControlKHR", System.Address, Attribute_Array, Errors.Error_Code); ----------------------------------------------------------------------------- -- Displays -- ----------------------------------------------------------------------------- package Get_Platform_Display is new Loading.Function_With_3_Params ("eglGetPlatformDisplayEXT", Objects.Displays.Platform_Kind, Void_Ptr, Int_Array, ID_Type); function Initialize_Display (Display : ID_Type; Major, Minor : out Int) return Bool with Import, Convention => C, External_Name => "eglInitialize"; function Terminate_Display (Display : ID_Type) return Bool with Import, Convention => C, External_Name => "eglTerminate"; function Query_String (No_Display : ID_Type; Name : Display_Query_Param) return C.Strings.chars_ptr with Import, Convention => C, External_Name => "eglQueryString"; -- Return a zero-terminated string with the properties of the EGL -- client or the EGL display, or null if an error occurred ----------------------------------------------------------------------------- -- Contexts -- ----------------------------------------------------------------------------- function Bind_API (API : Objects.Contexts.Client_API) return Bool with Import, Convention => C, External_Name => "eglBindAPI"; function Create_Context (Display : ID_Type; Config : ID_Type; Share : ID_Type; Attributes : Int_Array) return ID_Type with Import, Convention => C, External_Name => "eglCreateContext"; function Destroy_Context (Display : ID_Type; Context : ID_Type) return Bool with Import, Convention => C, External_Name => "eglDestroyContext"; function Make_Current (Display : ID_Type; Draw : ID_Type; Read : ID_Type; Context : ID_Type) return Bool with Import, Convention => C, External_Name => "eglMakeCurrent"; ----------------------------------------------------------------------------- -- Surfaces -- ----------------------------------------------------------------------------- -- eglSurfaceAttrib function Query_Surface (Display : ID_Type; Surface : ID_Type; Attribute : Surface_Query_Param; Value : out Int) return Bool with Import, Convention => C, External_Name => "eglQuerySurface"; function Query_Context (Display : ID_Type; Context : ID_Type; Attribute : Context_Query_Param; Value : out Objects.Contexts.Buffer_Kind) return Bool with Import, Convention => C, External_Name => "eglQueryContext"; function Get_Current_Context return ID_Type with Import, Convention => C, External_Name => "eglGetCurrentContext"; function Get_Config_Attrib (Display : ID_Type; Config : ID_Type; Attribute : Int; Value : out Int) return Bool with Import, Convention => C, External_Name => "eglGetConfigAttrib"; function Choose_Config (Display : ID_Type; Attributes : Int_Array; Configs : out ID_Array; Max_Configs : Int; Length : out Int) return Bool with Import, Convention => C, External_Name => "eglChooseConfig"; package Create_Platform_Window_Surface is new Loading.Function_With_4_Params ("eglCreatePlatformWindowSurfaceEXT", ID_Type, ID_Type, Native_Window_Ptr, Int_Array, ID_Type); function Destroy_Surface (Display : ID_Type; Surface : ID_Type) return Bool with Import, Convention => C, External_Name => "eglDestroySurface"; function Swap_Buffers (Display : ID_Type; Surface : ID_Type) return Bool with Import, Convention => C, External_Name => "eglSwapBuffers"; function Swap_Interval (Display : ID_Type; Interval : Int) return Bool with Import, Convention => C, External_Name => "eglSwapInterval"; ----------------------------------------------------------------------------- -- Devices -- ----------------------------------------------------------------------------- package Query_Device_String is new Loading.Function_With_2_Params ("eglQueryDeviceStringEXT", ID_Type, Device_Query_Param, C.Strings.chars_ptr); -- Return the DRM name of a device or a list of device extensions package Query_Display_Attrib is new Loading.Getter_With_3_Params ("eglQueryDisplayAttribEXT", ID_Type, Int, ID_Type, Bool); -- Return the device of a display package Query_Devices is new Loading.Array_Getter_With_3_Params ("eglQueryDevicesEXT", Int, ID_Type, ID_Array, Int, Bool); end EGL.API;
Fix with'ing of unused unit
egl: Fix with'ing of unused unit Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
e1855a8c01dc1d87663030e70ce24456054b8300
regtests/wiki-tests.adb
regtests/wiki-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 Util.Measures; with Wiki.Render.Wiki; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Plugins.Templates; with Wiki.Plugins.Conditions; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Documents; with Wiki.Parsers; package body Wiki.Tests is use Ada.Strings.Unbounded; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is use Ada.Directories; Result_File : constant String := To_String (T.Result); Dir : constant String := Containing_Directory (Result_File); Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter; Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream; type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record; -- Find a plugin knowing its name. overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access; overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is pragma Unreferenced (Factory); begin if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then return Condition'Unchecked_Access; else return Template.Find (Name); end if; end Find; Local_Factory : aliased Test_Factory; begin if not Exists (Dir) then Create_Path (Dir); end if; Input.Open (Path => To_String (T.File), Form => "WCEM=8"); Output.Create (Result_File, "WCEM=8"); Template.Set_Template_Path (Containing_Directory (To_String (T.File))); Condition.Append ("public", ""); Condition.Append ("user", "admin"); declare Time : Util.Measures.Stamp; begin Engine.Set_Syntax (T.Source); Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access); Engine.Add_Filter (Toc_Filter'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Parse (Input'Unchecked_Access, Doc); Util.Measures.Report (Time, "Parse " & To_String (T.Name)); if T.Source = Wiki.SYNTAX_HTML then declare Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name)); end; elsif T.Is_Html then declare Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render HTML " & To_String (T.Name)); end; else declare Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Text " & To_String (T.Name)); end; end if; end; Input.Close; 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.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.Wiki_Syntax; 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.Wiki_Syntax; 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.Wiki_Syntax; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.SYNTAX_MEDIA_WIKI; else Format := Wiki.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.Wiki_Syntax'Range loop case Syntax is when Wiki.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.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.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.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Plugins.Templates; with Wiki.Plugins.Conditions; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Documents; with Wiki.Parsers; package body Wiki.Tests is use Ada.Strings.Unbounded; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is use Ada.Directories; Result_File : constant String := To_String (T.Result); Dir : constant String := Containing_Directory (Result_File); Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter; Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream; type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record; -- Find a plugin knowing its name. overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access; overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is pragma Unreferenced (Factory); begin if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then return Condition'Unchecked_Access; else return Template.Find (Name); end if; end Find; Local_Factory : aliased Test_Factory; begin if not Exists (Dir) then Create_Path (Dir); end if; Input.Open (Path => To_String (T.File), Form => "WCEM=8"); Output.Create (Result_File, "WCEM=8"); Template.Set_Template_Path (Containing_Directory (To_String (T.File))); Condition.Append ("public", ""); Condition.Append ("user", "admin"); declare Time : Util.Measures.Stamp; begin Engine.Set_Syntax (T.Source); Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access); Engine.Add_Filter (Toc_Filter'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Parse (Input'Unchecked_Access, Doc); Util.Measures.Report (Time, "Parse " & To_String (T.Name)); if T.Source = Wiki.SYNTAX_HTML then declare Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name)); end; elsif T.Is_Html then declare Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render HTML " & To_String (T.Name)); end; else declare Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Text " & To_String (T.Name)); end; end if; end; Input.Close; 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.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.Wiki_Syntax; 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.Wiki_Syntax; 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.Wiki_Syntax; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.SYNTAX_MEDIA_WIKI; elsif Ext = "markdown" then Format := Wiki.SYNTAX_MARKDOWN; else Format := Wiki.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.Wiki_Syntax'Range loop case Syntax is when Wiki.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.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.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.Tests;
Add support for markdown unit tests
Add support for markdown unit tests
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
983684055ea44bbf47d4952c8ea4a454605f702b
src/asf-views-nodes-jsf.adb
src/asf-views-nodes-jsf.adb
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- 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 ASF.Converters; with ASF.Validators.Texts; with ASF.Validators.Numbers; with ASF.Components.Holders; with ASF.Components.Core.Views; package body ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- ------------------------------ -- Create the Converter Tag -- ------------------------------ function Create_Converter_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node; Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes, "converterId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Conv = null then Node.Error ("Missing 'converterId' attribute"); else Node.Converter := EL.Objects.To_Object (Conv.Value); end if; return Node.all'Access; end Create_Converter_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Holders; use type ASF.Converters.Converter_Access; Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter); begin if not (Parent.all in Value_Holder'Class) then Node.Error ("Parent component is not an instance of Value_Holder"); return; end if; if Cvt = null then Node.Error ("Converter was not found"); return; end if; declare VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access; begin VH.Set_Converter (Converter => Cvt); end; end Build_Components; -- ------------------------------ -- Validator Tag -- ------------------------------ -- ------------------------------ -- Create the Validator Tag -- ------------------------------ function Create_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node; Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes, "validatorId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Vid = null then Node.Error ("Missing 'validatorId' attribute"); else Node.Validator := EL.Objects.To_Object (Vid.Value); end if; return Node.all'Access; end Create_Validator_Tag_Node; -- ------------------------------ -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Holders; use type ASF.Validators.Validator_Access; V : Validators.Validator_Access; Shared : Boolean; begin if not (Parent.all in Editable_Value_Holder'Class) then Node.Error ("Parent component is not an instance of Editable_Value_Holder"); return; end if; Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared); if V = null then Node.Error ("Validator was not found"); return; end if; declare VH : constant access Editable_Value_Holder'Class := Editable_Value_Holder'Class (Parent.all)'Access; begin VH.Add_Validator (Validator => V, Shared => Shared); end; end Build_Components; -- ------------------------------ -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. -- ------------------------------ procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is begin Validator := Context.Get_Validator (Node.Validator); Shared := True; end Get_Validator; -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Range_Validator_Tag_Node; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is use type ASF.Validators.Validator_Access; Min : Long_Long_Integer := Long_Long_Integer'First; Max : Long_Long_Integer := Long_Long_Integer'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context)); end if; if Node.Maximum /= null then Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context)); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max)); return; end if; Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- ------------------------------ -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. -- ------------------------------ function Create_Length_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Length_Validator_Tag_Node; -- ------------------------------ -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. -- ------------------------------ overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is use type ASF.Validators.Validator_Access; Min : Natural := 0; Max : Natural := Natural'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context))); end if; if Node.Maximum /= null then Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context))); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Natural'Image (Min), Natural'Image (Max)); return; end if; Validator := Validators.Texts.Create_Length_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Attribute Tag -- ------------------------------ -- ------------------------------ -- Create the Attribute Tag -- ------------------------------ function Create_Attribute_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name"); Node : Attribute_Tag_Node_Access; begin Node := new Attribute_Tag_Node; Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Attr_Name := Attr; Node.Value := Find_Attribute (Attributes, "value"); if Node.Attr_Name = null then Node.Error ("Missing 'name' attribute"); else Node.Attr.Name := Attr.Value; end if; if Node.Value = null then Node.Error ("Missing 'value' attribute"); end if; return Node.all'Access; end Create_Attribute_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use EL.Expressions; begin if Node.Attr_Name /= null and Node.Value /= null then if Node.Value.Binding /= null then declare Expr : constant EL.Expressions.Expression := ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context); begin Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr); end; else Parent.Set_Attribute (Def => Node.Attr'Access, Value => Get_Value (Node.Value.all, Context)); end if; end if; end Build_Components; -- ------------------------------ -- Facet Tag -- ------------------------------ -- ------------------------------ -- Create the Facet Tag -- ------------------------------ function Create_Facet_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Facet_Name := Find_Attribute (Attributes, "name"); if Node.Facet_Name = null then Node.Error ("Missing 'name' attribute"); end if; return Node.all'Access; end Create_Facet_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. -- ------------------------------ overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is begin null; end Build_Components; -- ------------------------------ -- Metadata Tag -- ------------------------------ -- ------------------------------ -- Create the Metadata Tag -- ------------------------------ function Create_Metadata_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); return Node.all'Access; end Create_Metadata_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. -- ------------------------------ overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Core.Views; begin if not (Parent.all in UIView'Class) then Node.Error ("Parent component of <f:metadata> must be a <f:view>"); return; end if; declare UI : constant UIViewMetaData_Access := new UIViewMetaData; begin UIView'Class (Parent.all).Set_Metadata (UI, Node); Build_Attributes (UI.all, Node.all, Context); UI.Initialize (UI.Get_Context.all); Node.Build_Children (UI.all'Access, Context); end; end Build_Components; end ASF.Views.Nodes.Jsf;
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- 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.Beans.Objects; with ASF.Converters; with ASF.Validators.Texts; with ASF.Validators.Numbers; with ASF.Components.Holders; with ASF.Components.Core.Views; package body ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- ------------------------------ -- Create the Converter Tag -- ------------------------------ function Create_Converter_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node; Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes, "converterId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Conv = null then Node.Error ("Missing 'converterId' attribute"); else Node.Converter := EL.Objects.To_Object (Conv.Value); end if; return Node.all'Access; end Create_Converter_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Holders; use type ASF.Converters.Converter_Access; Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter); begin if not (Parent.all in Value_Holder'Class) then Node.Error ("Parent component is not an instance of Value_Holder"); return; end if; if Cvt = null then Node.Error ("Converter was not found"); return; end if; declare VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access; begin VH.Set_Converter (Converter => Cvt); end; end Build_Components; -- ------------------------------ -- Validator Tag -- ------------------------------ -- ------------------------------ -- Create the Validator Tag -- ------------------------------ function Create_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node; Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes, "validatorId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Vid = null then Node.Error ("Missing 'validatorId' attribute"); else Node.Validator := EL.Objects.To_Object (Vid.Value); end if; return Node.all'Access; end Create_Validator_Tag_Node; -- ------------------------------ -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Holders; use type ASF.Validators.Validator_Access; V : Validators.Validator_Access; Shared : Boolean; begin if not (Parent.all in Editable_Value_Holder'Class) then Node.Error ("Parent component is not an instance of Editable_Value_Holder"); return; end if; Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared); if V = null then Node.Error ("Validator was not found"); return; end if; declare VH : constant access Editable_Value_Holder'Class := Editable_Value_Holder'Class (Parent.all)'Access; begin VH.Add_Validator (Validator => V, Shared => Shared); end; end Build_Components; -- ------------------------------ -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. -- ------------------------------ procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is begin Validator := Context.Get_Validator (Node.Validator); Shared := True; end Get_Validator; -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Range_Validator_Tag_Node; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is use type ASF.Validators.Validator_Access; Min : Long_Long_Integer := Long_Long_Integer'First; Max : Long_Long_Integer := Long_Long_Integer'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context)); end if; if Node.Maximum /= null then Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context)); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max)); return; end if; Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- ------------------------------ -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. -- ------------------------------ function Create_Length_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Length_Validator_Tag_Node; -- ------------------------------ -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. -- ------------------------------ overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean) is use type ASF.Validators.Validator_Access; Min : Natural := 0; Max : Natural := Natural'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context))); end if; if Node.Maximum /= null then Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context))); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Natural'Image (Min), Natural'Image (Max)); return; end if; Validator := Validators.Texts.Create_Length_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Attribute Tag -- ------------------------------ -- ------------------------------ -- Create the Attribute Tag -- ------------------------------ function Create_Attribute_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name"); Node : Attribute_Tag_Node_Access; begin Node := new Attribute_Tag_Node; Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Attr_Name := Attr; Node.Value := Find_Attribute (Attributes, "value"); if Node.Attr_Name = null then Node.Error ("Missing 'name' attribute"); else Node.Attr.Name := Attr.Value; end if; if Node.Value = null then Node.Error ("Missing 'value' attribute"); end if; return Node.all'Access; end Create_Attribute_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. -- ------------------------------ overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use EL.Expressions; begin if Node.Attr_Name /= null and Node.Value /= null then if Node.Value.Binding /= null then declare Expr : constant EL.Expressions.Expression := ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context); begin Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr); end; else Parent.Set_Attribute (Def => Node.Attr'Access, Value => Get_Value (Node.Value.all, Context)); end if; end if; end Build_Components; -- ------------------------------ -- Facet Tag -- ------------------------------ -- ------------------------------ -- Create the Facet Tag -- ------------------------------ function Create_Facet_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Facet_Name := Find_Attribute (Attributes, "name"); if Node.Facet_Name = null then Node.Error ("Missing 'name' attribute"); end if; return Node.all'Access; end Create_Facet_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. -- ------------------------------ overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is Facet : constant UIComponent_Access := new UIComponent; Name : constant Util.Beans.Objects.Object := Get_Value (Node.Facet_Name.all, Context); begin Node.Build_Children (Facet, Context); Parent.Add_Facet (Util.Beans.Objects.To_String (Name), Facet.all'Access, Node); end Build_Components; -- ------------------------------ -- Metadata Tag -- ------------------------------ -- ------------------------------ -- Create the Metadata Tag -- ------------------------------ function Create_Metadata_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); return Node.all'Access; end Create_Metadata_Tag_Node; -- ------------------------------ -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. -- ------------------------------ overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class) is use ASF.Components.Core.Views; begin if not (Parent.all in UIView'Class) then Node.Error ("Parent component of <f:metadata> must be a <f:view>"); return; end if; declare UI : constant UIViewMetaData_Access := new UIViewMetaData; begin UIView'Class (Parent.all).Set_Metadata (UI, Node); Build_Attributes (UI.all, Node.all, Context); UI.Initialize (UI.Get_Context.all); Node.Build_Children (UI.all'Access, Context); end; end Build_Components; end ASF.Views.Nodes.Jsf;
Fix implementation of <f:facet> to build the facet tree component and associate it with the parent component under the given facet name
Fix implementation of <f:facet> to build the facet tree component and associate it with the parent component under the given facet name
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
7ae93dde6f5eafa719eec6d8263ad235a8b06954
src/portscan-packages.adb
src/portscan-packages.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Directories; with Util.Streams.Pipes; with Util.Streams.Buffered; package body PortScan.Packages is package AD renames Ada.Directories; package STR renames Util.Streams; ---------------------------- -- limited_sanity_check -- ---------------------------- procedure limited_sanity_check (repository : String) is procedure check_package (cursor : ranking_crate.Cursor); procedure check_package (cursor : ranking_crate.Cursor) is QR : constant queue_record := ranking_crate.Element (cursor); fullpath : constant String := repository & "/" & SU.To_String (all_ports (QR.ap_index).package_name); good : Boolean; begin if not AD.Exists (fullpath) then return; end if; good := passed_option_check (repository, QR.ap_index, True); if not good then TIO.Put_Line (get_catport (all_ports (QR.ap_index)) & " failed option check, removing ..."); return; end if; good := passed_dependency_check (repository, QR.ap_index, True); if not good then TIO.Put_Line (get_catport (all_ports (QR.ap_index)) & " failed dependency check, removing ..."); end if; end check_package; begin rank_queue.Iterate (check_package'Access); end limited_sanity_check; ------------------------ -- clean_repository -- ------------------------ procedure clean_repository (repository : String) is procedure save_package (cursor : ranking_crate.Cursor); procedure save_package (cursor : ranking_crate.Cursor) is QR : constant queue_record := ranking_crate.Element (cursor); pcc : package_crate.Cursor; use type package_crate.Cursor; begin pcc := stored_packages.Find (Key => all_ports (QR.ap_index).package_name); if pcc /= package_crate.No_Element then stored_packages.Delete (Position => pcc); end if; end save_package; begin scan_repository (repository); TIO.Put_Line ("Scanned"); rank_queue.Iterate (save_package'Access); declare cursor : package_crate.Cursor := stored_packages.First; use type package_crate.Cursor; begin while cursor /= package_crate.No_Element loop TIO.Put_Line ("remove " & SU.To_String (package_crate.Key (cursor))); cursor := package_crate.Next (cursor); end loop; end; end clean_repository; ----------------------- -- scan_repository -- ----------------------- procedure scan_repository (repository : String) is pkg_search : AD.Search_Type; dirent : AD.Directory_Entry_Type; begin stored_packages.Clear; AD.Start_Search (Search => pkg_search, Directory => repository, Filter => (AD.Ordinary_File => True, others => False), Pattern => ""); while AD.More_Entries (Search => pkg_search) loop AD.Get_Next_Entry (Search => pkg_search, Directory_Entry => dirent); declare pkgname : SU.Unbounded_String := SU.To_Unbounded_String (AD.Simple_Name (dirent)); begin stored_packages.Insert (Key => pkgname, New_Item => False); end; end loop; end scan_repository; --------------------------- -- passed_option_check -- --------------------------- function passed_option_check (repository : String; id : port_id; skip_exist_check : Boolean := False) return Boolean is begin if id = port_match_failed or else not all_ports (id).scanned then return False; end if; declare fullpath : constant String := repository & "/" & SU.To_String (all_ports (id).package_name); command : constant String := "pkg query -F " & fullpath & " %Ok:%Ov"; pipe : aliased STR.Pipes.Pipe_Stream; buffer : STR.Buffered.Buffered_Stream; content : SU.Unbounded_String; topline : SU.Unbounded_String; status : Integer; pkg_opts : package_crate.Map; colon : Natural; use type SU.Unbounded_String; begin if not skip_exist_check and then not AD.Exists (Name => fullpath) then return False; end if; pipe.Open (Command => command); buffer.Initialize (Output => null, Input => pipe'Unchecked_Access, Size => 4096); buffer.Read (Into => content); pipe.Close; status := pipe.Get_Exit_Status; if status /= 0 then raise pkgng_execution with "pkg options query " & SU.To_String (all_ports (id).package_name) & " (return code =" & status'Img & ")"; end if; loop nextline (lineblock => content, firstline => topline); exit when topline = SU.Null_Unbounded_String; colon := SU.Index (Source => topline, Pattern => ":"); if colon < 2 then raise unknown_format with SU.To_String (topline); end if; declare knob : String := SU.Slice (Source => topline, Low => colon + 1, High => SU.Length (topline)); name : SU.Unbounded_String := SU.To_Unbounded_String (SU.Slice (Source => topline, Low => 1, High => colon - 1)); insres : Boolean; dummy : package_crate.Cursor; begin if knob = "on" then pkg_opts.Insert (Key => name, New_Item => True, Position => dummy, Inserted => insres); elsif knob = "off" then pkg_opts.Insert (Key => name, New_Item => False, Position => dummy, Inserted => insres); else raise unknown_format with "knob=" & knob & "(" & SU.To_String (topline) & ")"; end if; end; end loop; declare num_opts : Natural := Natural (all_ports (id).options.Length); arrow : package_crate.Cursor; arrowkey : SU.Unbounded_String; knobval : Boolean; use type package_crate.Cursor; begin if num_opts /= Natural (pkg_opts.Length) then -- Different number of options, FAIL! return False; end if; arrow := pkg_opts.First; while arrow /= package_crate.No_Element loop arrowkey := package_crate.Key (arrow); knobval := pkg_opts.Element (arrowkey); if all_ports (id).options.Contains (arrowkey) then if knobval /= all_ports (id).options.Element (arrowkey) then -- port option value doesn't match package option value return False; end if; else -- Name of package option not found in port options return False; end if; arrow := package_crate.Next (arrow); end loop; end; -- If we get this far, the package options must match port options return True; end; end passed_option_check; ------------------------------- -- passed_dependency_check -- ------------------------------- function passed_dependency_check (repository : String; id : port_id; skip_exist_check : Boolean := False) return Boolean is begin if id = port_match_failed or else not all_ports (id).scanned then return False; end if; declare fullpath : constant String := repository & "/" & SU.To_String (all_ports (id).package_name); command : constant String := "pkg query -F " & fullpath & " %do:%dn-%dv"; pipe : aliased STR.Pipes.Pipe_Stream; buffer : STR.Buffered.Buffered_Stream; content : SU.Unbounded_String; topline : SU.Unbounded_String; status : Integer; colon : Natural; required : Natural := Natural (all_ports (id).librun.Length); counter : Natural := 0; use type SU.Unbounded_String; begin if not skip_exist_check and then not AD.Exists (Name => fullpath) then return False; end if; pipe.Open (Command => command); buffer.Initialize (Output => null, Input => pipe'Unchecked_Access, Size => 4096); buffer.Read (Into => content); pipe.Close; status := pipe.Get_Exit_Status; if status /= 0 then raise pkgng_execution with "pkg depends query " & SU.To_String (all_ports (id).package_name) & " (return code =" & status'Img & ")"; end if; loop nextline (lineblock => content, firstline => topline); exit when topline = SU.Null_Unbounded_String; colon := SU.Index (Source => topline, Pattern => ":"); if colon < 2 then raise unknown_format with SU.To_String (topline); end if; declare deppkg : String := SU.Slice (Source => topline, Low => colon + 1, High => SU.Length (topline)) & ".txz"; origin : SU.Unbounded_String := SU.To_Unbounded_String (SU.Slice (Source => topline, Low => 1, High => colon - 1)); target_id : port_index := ports_keys.Element (Key => origin); begin if target_id = port_match_failed then -- package has a dependency that has been removed from -- the ports tree return False; end if; counter := counter + 1; if counter > required then -- package has more dependencies than we are looking for return False; end if; if deppkg /= SU.To_String (all_ports (target_id).package_name) then -- The version that the package requires differs from the -- version that the ports tree will now produce return False; end if; end; end loop; if counter < required then -- The ports tree requires more dependencies than the existing -- package does return False; end if; -- If we get this far, the package dependencies match what the -- port tree requires exactly. This package passed sanity check. return True; end; end passed_dependency_check; --------------- -- nextline -- ---------------- procedure nextline (lineblock, firstline : out SU.Unbounded_String) is CR_loc : Natural; CR : constant String (1 .. 1) := (1 => Character'Val (10)); begin -- As long as the string isn't empty, we'll find a carriage return if SU.Length (lineblock) = 0 then firstline := SU.Null_Unbounded_String; return; end if; CR_loc := SU.Index (Source => lineblock, Pattern => CR); firstline := SU.To_Unbounded_String (Source => SU.Slice (Source => lineblock, Low => 1, High => CR_loc - 1)); SU.Delete (Source => lineblock, From => 1, Through => CR_loc); end nextline; end PortScan.Packages;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Directories; with Util.Streams.Pipes; with Util.Streams.Buffered; package body PortScan.Packages is package AD renames Ada.Directories; package STR renames Util.Streams; ---------------------------- -- limited_sanity_check -- ---------------------------- procedure limited_sanity_check (repository : String) is procedure check_package (cursor : ranking_crate.Cursor); procedure check_package (cursor : ranking_crate.Cursor) is QR : constant queue_record := ranking_crate.Element (cursor); fullpath : constant String := repository & "/" & SU.To_String (all_ports (QR.ap_index).package_name); good : Boolean; begin if not AD.Exists (fullpath) then return; end if; good := passed_option_check (repository, QR.ap_index, True); if not good then TIO.Put_Line (get_catport (all_ports (QR.ap_index)) & " failed option check, removing ..."); return; end if; good := passed_dependency_check (repository, QR.ap_index, True); if not good then TIO.Put_Line (get_catport (all_ports (QR.ap_index)) & " failed dependency check, removing ..."); end if; end check_package; begin rank_queue.Iterate (check_package'Access); end limited_sanity_check; ------------------------ -- clean_repository -- ------------------------ procedure clean_repository (repository : String) is procedure save_package (cursor : ranking_crate.Cursor); procedure save_package (cursor : ranking_crate.Cursor) is QR : constant queue_record := ranking_crate.Element (cursor); pcc : package_crate.Cursor; use type package_crate.Cursor; begin pcc := stored_packages.Find (Key => all_ports (QR.ap_index).package_name); if pcc /= package_crate.No_Element then stored_packages.Delete (Position => pcc); end if; end save_package; begin scan_repository (repository); TIO.Put_Line ("Scanned"); rank_queue.Iterate (save_package'Access); declare cursor : package_crate.Cursor := stored_packages.First; use type package_crate.Cursor; begin while cursor /= package_crate.No_Element loop TIO.Put_Line ("remove " & SU.To_String (package_crate.Key (cursor))); cursor := package_crate.Next (cursor); end loop; end; end clean_repository; ----------------------- -- scan_repository -- ----------------------- procedure scan_repository (repository : String) is pkg_search : AD.Search_Type; dirent : AD.Directory_Entry_Type; begin stored_packages.Clear; AD.Start_Search (Search => pkg_search, Directory => repository, Filter => (AD.Ordinary_File => True, others => False), Pattern => ""); while AD.More_Entries (Search => pkg_search) loop AD.Get_Next_Entry (Search => pkg_search, Directory_Entry => dirent); declare pkgname : SU.Unbounded_String := SU.To_Unbounded_String (AD.Simple_Name (dirent)); begin stored_packages.Insert (Key => pkgname, New_Item => False); end; end loop; end scan_repository; --------------------------- -- passed_option_check -- --------------------------- function passed_option_check (repository : String; id : port_id; skip_exist_check : Boolean := False) return Boolean is begin if id = port_match_failed or else not all_ports (id).scanned then return False; end if; declare fullpath : constant String := repository & "/" & SU.To_String (all_ports (id).package_name); command : constant String := "pkg query -F " & fullpath & " %Ok:%Ov"; pipe : aliased STR.Pipes.Pipe_Stream; buffer : STR.Buffered.Buffered_Stream; content : SU.Unbounded_String; topline : SU.Unbounded_String; status : Integer; colon : Natural; required : Natural := Natural (all_ports (id).options.Length); counter : Natural := 0; use type SU.Unbounded_String; begin if not skip_exist_check and then not AD.Exists (Name => fullpath) then return False; end if; pipe.Open (Command => command); buffer.Initialize (Output => null, Input => pipe'Unchecked_Access, Size => 4096); buffer.Read (Into => content); pipe.Close; status := pipe.Get_Exit_Status; if status /= 0 then raise pkgng_execution with "pkg options query " & SU.To_String (all_ports (id).package_name) & " (return code =" & status'Img & ")"; end if; loop nextline (lineblock => content, firstline => topline); exit when topline = SU.Null_Unbounded_String; colon := SU.Index (Source => topline, Pattern => ":"); if colon < 2 then raise unknown_format with SU.To_String (topline); end if; declare knob : String := SU.Slice (Source => topline, Low => colon + 1, High => SU.Length (topline)); namekey : SU.Unbounded_String := SU.To_Unbounded_String (SU.Slice (Source => topline, Low => 1, High => colon - 1)); knobval : Boolean; begin if knob = "on" then knobval := True; elsif knob = "off" then knobval := False; else raise unknown_format with "knob=" & knob & "(" & SU.To_String (topline) & ")"; end if; counter := counter + 1; if counter > required then -- package has more options than we are looking for return False; end if; if all_ports (id).options.Contains (namekey) then if knobval /= all_ports (id).options.Element (namekey) then -- port option value doesn't match package option value return False; end if; else -- Name of package option not found in port options return False; end if; end; end loop; if counter < required then -- The ports tree has more options than the existing package return False; end if; -- If we get this far, the package options must match port options return True; end; end passed_option_check; ------------------------------- -- passed_dependency_check -- ------------------------------- function passed_dependency_check (repository : String; id : port_id; skip_exist_check : Boolean := False) return Boolean is begin if id = port_match_failed or else not all_ports (id).scanned then return False; end if; declare fullpath : constant String := repository & "/" & SU.To_String (all_ports (id).package_name); command : constant String := "pkg query -F " & fullpath & " %do:%dn-%dv"; pipe : aliased STR.Pipes.Pipe_Stream; buffer : STR.Buffered.Buffered_Stream; content : SU.Unbounded_String; topline : SU.Unbounded_String; status : Integer; colon : Natural; required : Natural := Natural (all_ports (id).librun.Length); counter : Natural := 0; use type SU.Unbounded_String; begin if not skip_exist_check and then not AD.Exists (Name => fullpath) then return False; end if; pipe.Open (Command => command); buffer.Initialize (Output => null, Input => pipe'Unchecked_Access, Size => 4096); buffer.Read (Into => content); pipe.Close; status := pipe.Get_Exit_Status; if status /= 0 then raise pkgng_execution with "pkg depends query " & SU.To_String (all_ports (id).package_name) & " (return code =" & status'Img & ")"; end if; loop nextline (lineblock => content, firstline => topline); exit when topline = SU.Null_Unbounded_String; colon := SU.Index (Source => topline, Pattern => ":"); if colon < 2 then raise unknown_format with SU.To_String (topline); end if; declare deppkg : String := SU.Slice (Source => topline, Low => colon + 1, High => SU.Length (topline)) & ".txz"; origin : SU.Unbounded_String := SU.To_Unbounded_String (SU.Slice (Source => topline, Low => 1, High => colon - 1)); target_id : port_index := ports_keys.Element (Key => origin); begin if target_id = port_match_failed then -- package has a dependency that has been removed from -- the ports tree return False; end if; counter := counter + 1; if counter > required then -- package has more dependencies than we are looking for return False; end if; if deppkg /= SU.To_String (all_ports (target_id).package_name) then -- The version that the package requires differs from the -- version that the ports tree will now produce return False; end if; end; end loop; if counter < required then -- The ports tree requires more dependencies than the existing -- package does return False; end if; -- If we get this far, the package dependencies match what the -- port tree requires exactly. This package passed sanity check. return True; end; end passed_dependency_check; --------------- -- nextline -- ---------------- procedure nextline (lineblock, firstline : out SU.Unbounded_String) is CR_loc : Natural; CR : constant String (1 .. 1) := (1 => Character'Val (10)); begin -- As long as the string isn't empty, we'll find a carriage return if SU.Length (lineblock) = 0 then firstline := SU.Null_Unbounded_String; return; end if; CR_loc := SU.Index (Source => lineblock, Pattern => CR); firstline := SU.To_Unbounded_String (Source => SU.Slice (Source => lineblock, Low => 1, High => CR_loc - 1)); SU.Delete (Source => lineblock, From => 1, Through => CR_loc); end nextline; end PortScan.Packages;
Make options sanity check more efficient
Make options sanity check more efficient Using the template of the dependency check, rework the options check to avoid using a container.
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
abf5c1403de4c5226e7dde94de60db6e78d0259c
src/security-auth-oauth.ads
src/security-auth-oauth.ads
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- 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 Security.OAuth.Clients; private package Security.Auth.OAuth is -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. type Manager is abstract new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the OAuth access token and retrieve information about the user. procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is abstract; private type Manager is abstract new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; Scope : Unbounded_String; App : Security.OAuth.Clients.Application; end record; end Security.Auth.OAuth;
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- 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 Security.OAuth.Clients; private package Security.Auth.OAuth is -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. type Manager is abstract new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the OAuth access token and retrieve information about the user. procedure Verify_Access_Token (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Token : in Security.OAuth.Clients.Access_Token_Access; Result : in out Authentication) is abstract; private type Manager is abstract new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; Scope : Unbounded_String; Issuer : Unbounded_String; App : Security.OAuth.Clients.Application; end record; end Security.Auth.OAuth;
Add the issuer initialize from the configuration parameters
Add the issuer initialize from the configuration parameters
Ada
apache-2.0
stcarrez/ada-security
7d7449eecd73f737faf344a6b4d7f64a5f4df3b0
awa/plugins/awa-tags/src/model/awa-tags-models.ads
awa/plugins/awa-tags/src/model/awa-tags-models.ads
----------------------------------------------------------------------- -- AWA.Tags.Models -- AWA.Tags.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off, "unit * is not referenced"); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Basic.Lists; pragma Warnings (On, "unit * is not referenced"); package AWA.Tags.Models is type Tag_Ref is new ADO.Objects.Object_Ref with null record; type Tagged_Entity_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The tag definition. -- -------------------- -- Create an object key for Tag. function Tag_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Tag from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Tag_Key (Id : in String) return ADO.Objects.Object_Key; Null_Tag : constant Tag_Ref; function "=" (Left, Right : Tag_Ref'Class) return Boolean; -- Set the tag identifier procedure Set_Id (Object : in out Tag_Ref; Value : in ADO.Identifier); -- Get the tag identifier function Get_Id (Object : in Tag_Ref) return ADO.Identifier; -- Set the tag name procedure Set_Name (Object : in out Tag_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Name (Object : in out Tag_Ref; Value : in String); -- Get the tag name function Get_Name (Object : in Tag_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Name (Object : in Tag_Ref) return String; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Tag_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Tag_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Tag_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Tag_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Tag_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Tag_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition TAG_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Tag_Ref); -- Copy of the object. procedure Copy (Object : in Tag_Ref; Into : in out Tag_Ref); package Tag_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Tag_Ref, "=" => "="); subtype Tag_Vector is Tag_Vectors.Vector; procedure List (Object : in out Tag_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class); -- Create an object key for Tagged_Entity. function Tagged_Entity_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Tagged_Entity from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Tagged_Entity_Key (Id : in String) return ADO.Objects.Object_Key; Null_Tagged_Entity : constant Tagged_Entity_Ref; function "=" (Left, Right : Tagged_Entity_Ref'Class) return Boolean; -- Set the tag entity identifier procedure Set_Id (Object : in out Tagged_Entity_Ref; Value : in ADO.Identifier); -- Get the tag entity identifier function Get_Id (Object : in Tagged_Entity_Ref) return ADO.Identifier; -- Set Title: Tag model -- Date: 2013-02-23the database entity to which the tag is associated procedure Set_For_Entity_Id (Object : in out Tagged_Entity_Ref; Value : in ADO.Identifier); -- Get Title: Tag model -- Date: 2013-02-23the database entity to which the tag is associated function Get_For_Entity_Id (Object : in Tagged_Entity_Ref) return ADO.Identifier; -- Set the entity type procedure Set_Entity_Type (Object : in out Tagged_Entity_Ref; Value : in ADO.Entity_Type); -- Get the entity type function Get_Entity_Type (Object : in Tagged_Entity_Ref) return ADO.Entity_Type; -- procedure Set_Tag (Object : in out Tagged_Entity_Ref; Value : in AWA.Tags.Models.Tag_Ref'Class); -- function Get_Tag (Object : in Tagged_Entity_Ref) return AWA.Tags.Models.Tag_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Tagged_Entity_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition TAGGED_ENTITY_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Tagged_Entity_Ref); -- Copy of the object. procedure Copy (Object : in Tagged_Entity_Ref; Into : in out Tagged_Entity_Ref); package Tagged_Entity_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Tagged_Entity_Ref, "=" => "="); subtype Tagged_Entity_Vector is Tagged_Entity_Vectors.Vector; procedure List (Object : in out Tagged_Entity_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class); Query_Check_Tag : constant ADO.Queries.Query_Definition_Access; private TAG_NAME : aliased constant String := "awa_tag"; COL_0_1_NAME : aliased constant String := "id"; COL_1_1_NAME : aliased constant String := "name"; TAG_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 2, Table => TAG_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access ) ); TAG_TABLE : constant ADO.Schemas.Class_Mapping_Access := TAG_DEF'Access; Null_Tag : constant Tag_Ref := Tag_Ref'(ADO.Objects.Object_Ref with others => <>); type Tag_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => TAG_DEF'Access) with record Name : Ada.Strings.Unbounded.Unbounded_String; end record; type Tag_Access is access all Tag_Impl; overriding procedure Destroy (Object : access Tag_Impl); overriding procedure Find (Object : in out Tag_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Tag_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Tag_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Tag_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Tag_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Tag_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Tag_Ref'Class; Impl : out Tag_Access); TAGGED_ENTITY_NAME : aliased constant String := "awa_tagged_entity"; COL_0_2_NAME : aliased constant String := "id"; COL_1_2_NAME : aliased constant String := "for_entity_id"; COL_2_2_NAME : aliased constant String := "entity_type"; COL_3_2_NAME : aliased constant String := "tag_id"; TAGGED_ENTITY_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 4, Table => TAGGED_ENTITY_NAME'Access, Members => ( 1 => COL_0_2_NAME'Access, 2 => COL_1_2_NAME'Access, 3 => COL_2_2_NAME'Access, 4 => COL_3_2_NAME'Access ) ); TAGGED_ENTITY_TABLE : constant ADO.Schemas.Class_Mapping_Access := TAGGED_ENTITY_DEF'Access; Null_Tagged_Entity : constant Tagged_Entity_Ref := Tagged_Entity_Ref'(ADO.Objects.Object_Ref with others => <>); type Tagged_Entity_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => TAGGED_ENTITY_DEF'Access) with record For_Entity_Id : ADO.Identifier; Entity_Type : ADO.Entity_Type; Tag : AWA.Tags.Models.Tag_Ref; end record; type Tagged_Entity_Access is access all Tagged_Entity_Impl; overriding procedure Destroy (Object : access Tagged_Entity_Impl); overriding procedure Find (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Tagged_Entity_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Tagged_Entity_Ref'Class; Impl : out Tagged_Entity_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "tag-queries.xml", Sha1 => "9B2B599473F75F92CB5AB5045675E4CCEF926543"); package Def_Check_Tag is new ADO.Queries.Loaders.Query (Name => "check-tag", File => File_1.File'Access); Query_Check_Tag : constant ADO.Queries.Query_Definition_Access := Def_Check_Tag.Query'Access; end AWA.Tags.Models;
----------------------------------------------------------------------- -- AWA.Tags.Models -- AWA.Tags.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off, "unit * is not referenced"); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Basic.Lists; pragma Warnings (On, "unit * is not referenced"); package AWA.Tags.Models is type Tag_Ref is new ADO.Objects.Object_Ref with null record; type Tagged_Entity_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The tag definition. -- -------------------- -- Create an object key for Tag. function Tag_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Tag from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Tag_Key (Id : in String) return ADO.Objects.Object_Key; Null_Tag : constant Tag_Ref; function "=" (Left, Right : Tag_Ref'Class) return Boolean; -- Set the tag identifier procedure Set_Id (Object : in out Tag_Ref; Value : in ADO.Identifier); -- Get the tag identifier function Get_Id (Object : in Tag_Ref) return ADO.Identifier; -- Set the tag name procedure Set_Name (Object : in out Tag_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Name (Object : in out Tag_Ref; Value : in String); -- Get the tag name function Get_Name (Object : in Tag_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Name (Object : in Tag_Ref) return String; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Tag_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Tag_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Tag_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Tag_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Tag_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Tag_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition TAG_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Tag_Ref); -- Copy of the object. procedure Copy (Object : in Tag_Ref; Into : in out Tag_Ref); package Tag_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Tag_Ref, "=" => "="); subtype Tag_Vector is Tag_Vectors.Vector; procedure List (Object : in out Tag_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class); -- Create an object key for Tagged_Entity. function Tagged_Entity_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Tagged_Entity from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Tagged_Entity_Key (Id : in String) return ADO.Objects.Object_Key; Null_Tagged_Entity : constant Tagged_Entity_Ref; function "=" (Left, Right : Tagged_Entity_Ref'Class) return Boolean; -- Set the tag entity identifier procedure Set_Id (Object : in out Tagged_Entity_Ref; Value : in ADO.Identifier); -- Get the tag entity identifier function Get_Id (Object : in Tagged_Entity_Ref) return ADO.Identifier; -- Set Title: Tag model -- Date: 2013-02-23the database entity to which the tag is associated procedure Set_For_Entity_Id (Object : in out Tagged_Entity_Ref; Value : in ADO.Identifier); -- Get Title: Tag model -- Date: 2013-02-23the database entity to which the tag is associated function Get_For_Entity_Id (Object : in Tagged_Entity_Ref) return ADO.Identifier; -- Set the entity type procedure Set_Entity_Type (Object : in out Tagged_Entity_Ref; Value : in ADO.Entity_Type); -- Get the entity type function Get_Entity_Type (Object : in Tagged_Entity_Ref) return ADO.Entity_Type; -- procedure Set_Tag (Object : in out Tagged_Entity_Ref; Value : in AWA.Tags.Models.Tag_Ref'Class); -- function Get_Tag (Object : in Tagged_Entity_Ref) return AWA.Tags.Models.Tag_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Tagged_Entity_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Tagged_Entity_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition TAGGED_ENTITY_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Tagged_Entity_Ref); -- Copy of the object. procedure Copy (Object : in Tagged_Entity_Ref; Into : in out Tagged_Entity_Ref); package Tagged_Entity_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Tagged_Entity_Ref, "=" => "="); subtype Tagged_Entity_Vector is Tagged_Entity_Vectors.Vector; procedure List (Object : in out Tagged_Entity_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class); Query_Check_Tag : constant ADO.Queries.Query_Definition_Access; Query_Tag_List : constant ADO.Queries.Query_Definition_Access; private TAG_NAME : aliased constant String := "awa_tag"; COL_0_1_NAME : aliased constant String := "id"; COL_1_1_NAME : aliased constant String := "name"; TAG_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 2, Table => TAG_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access ) ); TAG_TABLE : constant ADO.Schemas.Class_Mapping_Access := TAG_DEF'Access; Null_Tag : constant Tag_Ref := Tag_Ref'(ADO.Objects.Object_Ref with others => <>); type Tag_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => TAG_DEF'Access) with record Name : Ada.Strings.Unbounded.Unbounded_String; end record; type Tag_Access is access all Tag_Impl; overriding procedure Destroy (Object : access Tag_Impl); overriding procedure Find (Object : in out Tag_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Tag_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Tag_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Tag_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Tag_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Tag_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Tag_Ref'Class; Impl : out Tag_Access); TAGGED_ENTITY_NAME : aliased constant String := "awa_tagged_entity"; COL_0_2_NAME : aliased constant String := "id"; COL_1_2_NAME : aliased constant String := "for_entity_id"; COL_2_2_NAME : aliased constant String := "entity_type"; COL_3_2_NAME : aliased constant String := "tag_id"; TAGGED_ENTITY_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 4, Table => TAGGED_ENTITY_NAME'Access, Members => ( 1 => COL_0_2_NAME'Access, 2 => COL_1_2_NAME'Access, 3 => COL_2_2_NAME'Access, 4 => COL_3_2_NAME'Access ) ); TAGGED_ENTITY_TABLE : constant ADO.Schemas.Class_Mapping_Access := TAGGED_ENTITY_DEF'Access; Null_Tagged_Entity : constant Tagged_Entity_Ref := Tagged_Entity_Ref'(ADO.Objects.Object_Ref with others => <>); type Tagged_Entity_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => TAGGED_ENTITY_DEF'Access) with record For_Entity_Id : ADO.Identifier; Entity_Type : ADO.Entity_Type; Tag : AWA.Tags.Models.Tag_Ref; end record; type Tagged_Entity_Access is access all Tagged_Entity_Impl; overriding procedure Destroy (Object : access Tagged_Entity_Impl); overriding procedure Find (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Tagged_Entity_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Tagged_Entity_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Tagged_Entity_Ref'Class; Impl : out Tagged_Entity_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "tag-queries.xml", Sha1 => "9B2B599473F75F92CB5AB5045675E4CCEF926543"); package Def_Check_Tag is new ADO.Queries.Loaders.Query (Name => "check-tag", File => File_1.File'Access); Query_Check_Tag : constant ADO.Queries.Query_Definition_Access := Def_Check_Tag.Query'Access; package Def_Tag_List is new ADO.Queries.Loaders.Query (Name => "tag-list", File => File_1.File'Access); Query_Tag_List : constant ADO.Queries.Query_Definition_Access := Def_Tag_List.Query'Access; end AWA.Tags.Models;
Rebuild the model files
Rebuild the model files
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
81fb0246c0cc60ac2cbfaa5316763b4a1b217d3a
src/ado-sequences-hilo.ads
src/ado-sequences-hilo.ads
----------------------------------------------------------------------- -- ADO Sequences Hilo-- HiLo Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- === HiLo Sequence Generator === -- The HiLo sequence generator. This sequence generator uses a database table -- <b>sequence</b> to allocate blocks of identifiers for a given sequence name. -- The sequence table contains one row for each sequence. It keeps track of -- the next available sequence identifier (in the <b>value</b> column). -- -- To allocate a sequence block, the HiLo generator obtains the next available -- sequence identified and updates it by adding the sequence block size. The -- HiLo sequence generator will allocate the identifiers until the block is -- full after which a new block will be allocated. package ADO.Sequences.Hilo is -- ------------------------------ -- High Low sequence generator -- ------------------------------ type HiLoGenerator is new Generator with private; DEFAULT_BLOCK_SIZE : constant Identifier := 100; -- Allocate an identifier using the generator. -- The generator allocates blocks of sequences by using a sequence -- table stored in the database. One database access is necessary -- every N allocations. overriding procedure Allocate (Gen : in out HiLoGenerator; Id : in out Objects.Object_Record'Class); -- Allocate a new sequence block. procedure Allocate_Sequence (Gen : in out HiLoGenerator); function Create_HiLo_Generator (Sess_Factory : in Session_Factory_Access) return Generator_Access; private type HiLoGenerator is new Generator with record Last_Id : Identifier := NO_IDENTIFIER; Next_Id : Identifier := NO_IDENTIFIER; Block_Size : Identifier := DEFAULT_BLOCK_SIZE; end record; end ADO.Sequences.Hilo;
----------------------------------------------------------------------- -- ADO Sequences Hilo-- HiLo Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- === HiLo Sequence Generator === -- The HiLo sequence generator. This sequence generator uses a database table -- `sequence` to allocate blocks of identifiers for a given sequence name. -- The sequence table contains one row for each sequence. It keeps track of -- the next available sequence identifier (in the `value column). -- -- To allocate a sequence block, the HiLo generator obtains the next available -- sequence identified and updates it by adding the sequence block size. The -- HiLo sequence generator will allocate the identifiers until the block is -- full after which a new block will be allocated. package ADO.Sequences.Hilo is -- ------------------------------ -- High Low sequence generator -- ------------------------------ type HiLoGenerator is new Generator with private; DEFAULT_BLOCK_SIZE : constant Identifier := 100; -- Allocate an identifier using the generator. -- The generator allocates blocks of sequences by using a sequence -- table stored in the database. One database access is necessary -- every N allocations. overriding procedure Allocate (Gen : in out HiLoGenerator; Id : in out Objects.Object_Record'Class); -- Allocate a new sequence block. procedure Allocate_Sequence (Gen : in out HiLoGenerator); function Create_HiLo_Generator (Sess_Factory : in Session_Factory_Access) return Generator_Access; private type HiLoGenerator is new Generator with record Last_Id : Identifier := NO_IDENTIFIER; Next_Id : Identifier := NO_IDENTIFIER; Block_Size : Identifier := DEFAULT_BLOCK_SIZE; end record; end ADO.Sequences.Hilo;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
516cf536e7321bb11c789cb4eb304d8d6eee8241
src/asf-models-selects.adb
src/asf-models-selects.adb
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body ASF.Models.Selects is -- ------------------------------ -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. -- ------------------------------ function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object is begin if Item.Item.Is_Null then return Util.Beans.Objects.Null_Object; else declare Bean : constant Select_Item_Access := new Select_Item; begin Bean.all := Item; return Util.Beans.Objects.To_Object (Bean.all'Access); end; end if; end To_Object; -- ------------------------------ -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. -- ------------------------------ function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Object); Result : Select_Item; begin if Bean = null then return Result; end if; if not (Bean.all in Select_Item'Class) then return Result; end if; Result := Select_Item (Bean.all); return Result; end To_Select_Item; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label and value. -- ------------------------------ function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is use Ada.Characters.Conversions; Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin Item.Label := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Label)); Item.Value := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Value)); Item.Description := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Description)); Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label and value. -- ------------------------------ function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin Item.Label := To_Unbounded_Wide_Wide_String (Label); Item.Value := To_Unbounded_Wide_Wide_String (Value); Item.Description := To_Unbounded_Wide_Wide_String (Description); Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item_Wide; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. -- ------------------------------ function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is use Util.Beans.Objects; Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin if not Is_Null (Label) then Item.Label := To_Unbounded_Wide_Wide_String (Label); end if; if not Is_Null (Value) then Item.Value := To_Unbounded_Wide_Wide_String (Value); end if; if not Is_Null (Description) then Item.Description := To_Unbounded_Wide_Wide_String (Description); end if; Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item; -- ------------------------------ -- Get the item label. -- ------------------------------ function Get_Label (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Label); end if; end Get_Label; -- ------------------------------ -- Get the item value. -- ------------------------------ function Get_Value (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Value); end if; end Get_Value; -- ------------------------------ -- Get the item description. -- ------------------------------ function Get_Description (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Description); end if; end Get_Description; -- ------------------------------ -- Returns true if the item is disabled. -- ------------------------------ function Is_Disabled (Item : in Select_Item) return Boolean is begin if Item.Item.Is_Null then return False; else return Item.Item.Value.Disabled; end if; end Is_Disabled; -- ------------------------------ -- Returns true if the label must be escaped using HTML escape rules. -- ------------------------------ function Is_Escaped (Item : in Select_Item) return Boolean is begin if Item.Item.Is_Null then return False; else return Item.Item.Value.Escape; end if; end Is_Escaped; -- ------------------------------ -- Returns true if the select item component is empty. -- ------------------------------ function Is_Empty (Item : in Select_Item) return Boolean is begin return Item.Item.Is_Null; end Is_Empty; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Select_Item; Name : in String) return Util.Beans.Objects.Object is begin if From.Item.Is_Null then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Select_Item_Record_Access := From.Item.Value; begin if Name = "name" then return Util.Beans.Objects.To_Object (Item.Label); elsif Name = "value" then return Util.Beans.Objects.To_Object (Item.Value); elsif Name = "description" then return Util.Beans.Objects.To_Object (Item.Description); elsif Name = "disabled" then return Util.Beans.Objects.To_Object (Item.Disabled); elsif Name = "escaped" then return Util.Beans.Objects.To_Object (Item.Escape); else return Util.Beans.Objects.Null_Object; end if; end; end Get_Value; -- ------------------------------ -- Select Item List -- ------------------------------ -- ------------------------------ -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. -- ------------------------------ function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object is begin if Item.List.Is_Null then return Util.Beans.Objects.Null_Object; else declare Bean : constant Select_Item_List_Access := new Select_Item_List; begin Bean.all := Item; return Util.Beans.Objects.To_Object (Bean.all'Access); end; end if; end To_Object; -- ------------------------------ -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. -- ------------------------------ function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Object); Result : Select_Item_List; begin if Bean = null then return Result; end if; if not (Bean.all in Select_Item_List'Class) then return Result; end if; Result := Select_Item_List (Bean.all); return Result; end To_Select_Item_List; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Select_Item_List) return Natural is begin return From.Length; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Select_Item_List; Index : in Natural) is begin From.Current := From.Get_Select_Item (Index); From.Row := Util.Beans.Objects.To_Object (From.Current'Unchecked_Access, Util.Beans.Objects.STATIC); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Select_Item_List) return Util.Beans.Objects.Object is begin return From.Row; end Get_Row; -- ------------------------------ -- Get the number of items in the list. -- ------------------------------ function Length (List : in Select_Item_List) return Natural is begin if List.List.Is_Null then return 0; else return Natural (List.List.Value.List.Length); end if; end Length; -- ------------------------------ -- Get the select item from the list -- ------------------------------ function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item is begin if List.List.Is_Null then raise Constraint_Error with "Select item list is empty"; end if; return List.List.Value.List.Element (Pos); end Get_Select_Item; -- ------------------------------ -- Add the item at the end of the list. -- ------------------------------ procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class) is begin if List.List.Is_Null then List.List := Select_Item_Vector_Refs.Create; end if; List.List.Value.all.List.Append (Select_Item (Item)); end Append; -- ------------------------------ -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) -- ------------------------------ procedure Append (List : in out Select_Item_List; Label : in String; Value : in String) is begin List.Append (Create_Select_Item (Label, Value)); end Append; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Select_Item_List; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; end ASF.Models.Selects;
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; package body ASF.Models.Selects is function UTF8_Decode (S : in String) return Wide_Wide_String renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode; -- ------------------------------ -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. -- ------------------------------ function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object is begin if Item.Item.Is_Null then return Util.Beans.Objects.Null_Object; else declare Bean : constant Select_Item_Access := new Select_Item; begin Bean.all := Item; return Util.Beans.Objects.To_Object (Bean.all'Access); end; end if; end To_Object; -- ------------------------------ -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. -- ------------------------------ function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Object); Result : Select_Item; begin if Bean = null then return Result; end if; if not (Bean.all in Select_Item'Class) then return Result; end if; Result := Select_Item (Bean.all); return Result; end To_Select_Item; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label and value. -- ------------------------------ function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin Item.Label := To_Unbounded_Wide_Wide_String (UTF8_Decode (Label)); Item.Value := To_Unbounded_Wide_Wide_String (UTF8_Decode (Value)); Item.Description := To_Unbounded_Wide_Wide_String (UTF8_Decode (Description)); Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label and value. -- ------------------------------ function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin Item.Label := To_Unbounded_Wide_Wide_String (Label); Item.Value := To_Unbounded_Wide_Wide_String (Value); Item.Description := To_Unbounded_Wide_Wide_String (Description); Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item_Wide; -- ------------------------------ -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. -- ------------------------------ function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item is use Util.Beans.Objects; Result : Select_Item; begin Result.Item := Select_Item_Refs.Create; declare Item : constant Select_Item_Record_Access := Result.Item.Value; begin if not Is_Null (Label) then Item.Label := To_Unbounded_Wide_Wide_String (Label); end if; if not Is_Null (Value) then Item.Value := To_Unbounded_Wide_Wide_String (Value); end if; if not Is_Null (Description) then Item.Description := To_Unbounded_Wide_Wide_String (Description); end if; Item.Disabled := Disabled; Item.Escape := Escaped; end; return Result; end Create_Select_Item; -- ------------------------------ -- Get the item label. -- ------------------------------ function Get_Label (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Label); end if; end Get_Label; -- ------------------------------ -- Get the item value. -- ------------------------------ function Get_Value (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Value); end if; end Get_Value; -- ------------------------------ -- Get the item description. -- ------------------------------ function Get_Description (Item : in Select_Item) return Wide_Wide_String is begin if Item.Item.Is_Null then return ""; else return To_Wide_Wide_String (Item.Item.Value.Description); end if; end Get_Description; -- ------------------------------ -- Returns true if the item is disabled. -- ------------------------------ function Is_Disabled (Item : in Select_Item) return Boolean is begin if Item.Item.Is_Null then return False; else return Item.Item.Value.Disabled; end if; end Is_Disabled; -- ------------------------------ -- Returns true if the label must be escaped using HTML escape rules. -- ------------------------------ function Is_Escaped (Item : in Select_Item) return Boolean is begin if Item.Item.Is_Null then return False; else return Item.Item.Value.Escape; end if; end Is_Escaped; -- ------------------------------ -- Returns true if the select item component is empty. -- ------------------------------ function Is_Empty (Item : in Select_Item) return Boolean is begin return Item.Item.Is_Null; end Is_Empty; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Select_Item; Name : in String) return Util.Beans.Objects.Object is begin if From.Item.Is_Null then return Util.Beans.Objects.Null_Object; end if; declare Item : constant Select_Item_Record_Access := From.Item.Value; begin if Name = "name" then return Util.Beans.Objects.To_Object (Item.Label); elsif Name = "value" then return Util.Beans.Objects.To_Object (Item.Value); elsif Name = "description" then return Util.Beans.Objects.To_Object (Item.Description); elsif Name = "disabled" then return Util.Beans.Objects.To_Object (Item.Disabled); elsif Name = "escaped" then return Util.Beans.Objects.To_Object (Item.Escape); else return Util.Beans.Objects.Null_Object; end if; end; end Get_Value; -- ------------------------------ -- Select Item List -- ------------------------------ -- ------------------------------ -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. -- ------------------------------ function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object is begin if Item.List.Is_Null then return Util.Beans.Objects.Null_Object; else declare Bean : constant Select_Item_List_Access := new Select_Item_List; begin Bean.all := Item; return Util.Beans.Objects.To_Object (Bean.all'Access); end; end if; end To_Object; -- ------------------------------ -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. -- ------------------------------ function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Object); Result : Select_Item_List; begin if Bean = null then return Result; end if; if not (Bean.all in Select_Item_List'Class) then return Result; end if; Result := Select_Item_List (Bean.all); return Result; end To_Select_Item_List; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Select_Item_List) return Natural is begin return From.Length; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Select_Item_List; Index : in Natural) is begin From.Current := From.Get_Select_Item (Index); From.Row := Util.Beans.Objects.To_Object (From.Current'Unchecked_Access, Util.Beans.Objects.STATIC); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Select_Item_List) return Util.Beans.Objects.Object is begin return From.Row; end Get_Row; -- ------------------------------ -- Get the number of items in the list. -- ------------------------------ function Length (List : in Select_Item_List) return Natural is begin if List.List.Is_Null then return 0; else return Natural (List.List.Value.List.Length); end if; end Length; -- ------------------------------ -- Get the select item from the list -- ------------------------------ function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item is begin if List.List.Is_Null then raise Constraint_Error with "Select item list is empty"; end if; return List.List.Value.List.Element (Pos); end Get_Select_Item; -- ------------------------------ -- Add the item at the end of the list. -- ------------------------------ procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class) is begin if List.List.Is_Null then List.List := Select_Item_Vector_Refs.Create; end if; List.List.Value.all.List.Append (Select_Item (Item)); end Append; -- ------------------------------ -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) -- ------------------------------ procedure Append (List : in out Select_Item_List; Label : in String; Value : in String) is begin List.Append (Create_Select_Item (Label, Value)); end Append; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Select_Item_List; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; end ASF.Models.Selects;
Use Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode for the String to Wide_Wide_String conversion so that UTF-8 sequences are converted correctly
Use Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode for the String to Wide_Wide_String conversion so that UTF-8 sequences are converted correctly
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b9dc1f7f45a3be1253841c32eb6974ad768eeeab
src/asf-models-selects.ads
src/asf-models-selects.ads
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Refs; package ASF.Models.Selects is -- ------------------------------ -- Select Item -- ------------------------------ -- The <b>Select_Item</b> type describes a single option of a list of options -- used by the <b>UISelectOne</b> or <b>UISelectMany</b> components. -- The select item contains: -- <ul> -- <li>A label -- <li>A value -- <li>A description -- <li>Whether the select item is disabled or not -- <li>Whether the label is escaped or not -- </ul> -- An application creates the <b>Select_Item</b> instances and passes them -- to the ASF components through an <b>Util.Beans.Objects.Object</b> value. type Select_Item is new Util.Beans.Basic.Readonly_Bean with private; type Select_Item_Access is access all Select_Item; -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object; -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Get the item label. function Get_Label (Item : in Select_Item) return Wide_Wide_String; -- Get the item value. function Get_Value (Item : in Select_Item) return Wide_Wide_String; -- Get the item description. function Get_Description (Item : in Select_Item) return Wide_Wide_String; -- Returns true if the item is disabled. function Is_Disabled (Item : in Select_Item) return Boolean; -- Returns true if the label must be escaped using HTML escape rules. function Is_Escaped (Item : in Select_Item) return Boolean; -- Returns true if the select item component is empty. function Is_Empty (Item : in Select_Item) return Boolean; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Select_Item; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Select Item List -- ------------------------------ -- The <b>Select_Item_List</b> type holds a list of <b>Select_Item</b>. -- Similar to <b>Select_Item</b>, an application builds the list items and gives it -- to the ASF components through an <b>Util.Beans.Objects.Object</b> instance. type Select_Item_List is new Util.Beans.Basic.Readonly_Bean with private; type Select_Item_List_Access is access all Select_Item_List; -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object; -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List; -- Get the number of items in the list. function Length (List : in Select_Item_List) return Natural; -- Get the select item from the list function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item; -- Add the item at the end of the list. procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class); -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) procedure Append (List : in out Select_Item_List; Label : in String; Value : in String); private use Ada.Strings.Wide_Wide_Unbounded; type Select_Item_Record is new Util.Refs.Ref_Entity with record Label : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; Description : Unbounded_Wide_Wide_String; Disabled : Boolean := False; Escape : Boolean := False; end record; type Select_Item_Record_Access is access all Select_Item_Record; package Select_Item_Refs is new Util.Refs.References (Element_Type => Select_Item_Record, Element_Access => Select_Item_Record_Access); type Select_Item is new Util.Beans.Basic.Readonly_Bean with record Item : Select_Item_Refs.Ref; end record; package Select_Item_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Select_Item); type Select_Item_Vector is new Util.Refs.Ref_Entity with record List : Select_Item_Vectors.Vector; end record; type Select_Item_Vector_Access is access all Select_Item_Vector; package Select_Item_Vector_Refs is new Util.Refs.References (Element_Type => Select_Item_Vector, Element_Access => Select_Item_Vector_Access); type Select_Item_List is new Util.Beans.Basic.Readonly_Bean with record List : Select_Item_Vector_Refs.Ref; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Select_Item_List; Name : in String) return Util.Beans.Objects.Object; end ASF.Models.Selects;
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Refs; package ASF.Models.Selects is -- ------------------------------ -- Select Item -- ------------------------------ -- The <b>Select_Item</b> type describes a single option of a list of options -- used by the <b>UISelectOne</b> or <b>UISelectMany</b> components. -- The select item contains: -- <ul> -- <li>A label -- <li>A value -- <li>A description -- <li>Whether the select item is disabled or not -- <li>Whether the label is escaped or not -- </ul> -- An application creates the <b>Select_Item</b> instances and passes them -- to the ASF components through an <b>Util.Beans.Objects.Object</b> value. type Select_Item is new Util.Beans.Basic.Readonly_Bean with private; type Select_Item_Access is access all Select_Item; -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object; -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Get the item label. function Get_Label (Item : in Select_Item) return Wide_Wide_String; -- Get the item value. function Get_Value (Item : in Select_Item) return Wide_Wide_String; -- Get the item description. function Get_Description (Item : in Select_Item) return Wide_Wide_String; -- Returns true if the item is disabled. function Is_Disabled (Item : in Select_Item) return Boolean; -- Returns true if the label must be escaped using HTML escape rules. function Is_Escaped (Item : in Select_Item) return Boolean; -- Returns true if the select item component is empty. function Is_Empty (Item : in Select_Item) return Boolean; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Select_Item; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Select Item List -- ------------------------------ -- The <b>Select_Item_List</b> type holds a list of <b>Select_Item</b>. -- Similar to <b>Select_Item</b>, an application builds the list items and gives it -- to the ASF components through an <b>Util.Beans.Objects.Object</b> instance. type Select_Item_List is new Util.Beans.Basic.List_Bean with private; type Select_Item_List_Access is access all Select_Item_List; -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object; -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List; -- Get the number of elements in the list. overriding function Get_Count (From : in Select_Item_List) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out Select_Item_List; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in Select_Item_List) return Util.Beans.Objects.Object; -- Get the number of items in the list. function Length (List : in Select_Item_List) return Natural; -- Get the select item from the list function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item; -- Add the item at the end of the list. procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class); -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) procedure Append (List : in out Select_Item_List; Label : in String; Value : in String); private use Ada.Strings.Wide_Wide_Unbounded; type Select_Item_Record is new Util.Refs.Ref_Entity with record Label : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; Description : Unbounded_Wide_Wide_String; Disabled : Boolean := False; Escape : Boolean := False; end record; type Select_Item_Record_Access is access all Select_Item_Record; package Select_Item_Refs is new Util.Refs.References (Element_Type => Select_Item_Record, Element_Access => Select_Item_Record_Access); type Select_Item is new Util.Beans.Basic.Readonly_Bean with record Item : Select_Item_Refs.Ref; end record; package Select_Item_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Select_Item); type Select_Item_Vector is new Util.Refs.Ref_Entity with record List : Select_Item_Vectors.Vector; end record; type Select_Item_Vector_Access is access all Select_Item_Vector; package Select_Item_Vector_Refs is new Util.Refs.References (Element_Type => Select_Item_Vector, Element_Access => Select_Item_Vector_Access); type Select_Item_List is new Util.Beans.Basic.List_Bean with record List : Select_Item_Vector_Refs.Ref; Current : aliased Select_Item; Row : Util.Beans.Objects.Object; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Select_Item_List; Name : in String) return Util.Beans.Objects.Object; end ASF.Models.Selects;
Change the Select_List_Item to implement the List_Bean interface so that a select list can be used as general purpose lists also
Change the Select_List_Item to implement the List_Bean interface so that a select list can be used as general purpose lists also
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
5faedf860593866837de296b865c6bfdf5487438
src/asf-applications-main.ads
src/asf-applications-main.ads
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Locales; with EL.Objects; with EL.Contexts; with EL.Functions; with EL.Functions.Default; with EL.Expressions; with EL.Variables.Default; with Ada.Strings.Unbounded; with ASF.Locales; with ASF.Factory; with ASF.Converters; with ASF.Validators; with ASF.Contexts.Faces; with ASF.Contexts.Exceptions; with ASF.Lifecycles; with ASF.Applications.Views; with ASF.Navigations; with ASF.Beans; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Events.Faces.Actions; with Security.Policies; use Security; with Security.OAuth.Servers; package ASF.Applications.Main is use ASF.Beans; -- ------------------------------ -- Factory for creation of lifecycle, view handler -- ------------------------------ type Application_Factory is tagged limited private; -- Create the lifecycle handler. The lifecycle handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object. -- It can be overriden to change the behavior of the ASF request lifecycle. function Create_Lifecycle_Handler (App : in Application_Factory) return ASF.Lifecycles.Lifecycle_Access; -- Create the view handler. The view handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Applications.Views.View_Handler</b> object. -- It can be overriden to change the views associated with the application. function Create_View_Handler (App : in Application_Factory) return ASF.Applications.Views.View_Handler_Access; -- Create the navigation handler. The navigation handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Navigations.Navigation_Handler</b> object. -- It can be overriden to change the navigations associated with the application. function Create_Navigation_Handler (App : in Application_Factory) return ASF.Navigations.Navigation_Handler_Access; -- Create the security policy manager. The security policy manager is created during -- the initialization phase of the application. The default implementation -- creates a <b>Security.Policies.Policy_Manager</b> object. function Create_Security_Manager (App : in Application_Factory) return Security.Policies.Policy_Manager_Access; -- Create the OAuth application manager. The OAuth application manager is created -- during the initialization phase of the application. The default implementation -- creates a <b>Security.OAuth.Servers.Auth_Manager</b> object. function Create_OAuth_Manager (App : in Application_Factory) return Security.OAuth.Servers.Auth_Manager_Access; -- Create the exception handler. The exception handler is created during -- the initialization phase of the application. The default implementation -- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object. function Create_Exception_Handler (App : in Application_Factory) return ASF.Contexts.Exceptions.Exception_Handler_Access; -- ------------------------------ -- Application -- ------------------------------ type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with private; type Application_Access is access all Application'Class; -- Get the application view handler. function Get_View_Handler (App : access Application) return access Views.View_Handler'Class; -- Get the lifecycle handler. function Get_Lifecycle_Handler (App : in Application) return ASF.Lifecycles.Lifecycle_Access; -- Get the navigation handler. function Get_Navigation_Handler (App : in Application) return ASF.Navigations.Navigation_Handler_Access; -- Get the permission manager associated with this application. function Get_Security_Manager (App : in Application) return Security.Policies.Policy_Manager_Access; -- Get the action event listener responsible for processing action -- events and triggering the navigation to the next view using the -- navigation handler. function Get_Action_Listener (App : in Application) return ASF.Events.Faces.Actions.Action_Listener_Access; -- Process the action associated with the action event. The action returns -- and outcome which is then passed to the navigation handler to navigate to -- the next view. overriding procedure Process_Action (Listener : in Application; Event : in ASF.Events.Faces.Actions.Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class); -- Execute the action method. The action returns and outcome which is then passed -- to the navigation handler to navigate to the next view. procedure Process_Action (Listener : in Application; Method : in EL.Expressions.Method_Info; Context : in out Contexts.Faces.Faces_Context'Class); -- Initialize the application procedure Initialize (App : in out Application; Conf : in Config; Factory : in out Application_Factory'Class); -- 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. procedure Initialize_Components (App : in out Application); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. procedure Initialize_Config (App : in out Application; Conf : in out Config); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. procedure Initialize_Filters (App : in out Application); -- Finalizes the application, freeing the memory. overriding procedure Finalize (App : in out Application); -- Get the configuration parameter; function Get_Config (App : Application; Param : Config_Param) return String; -- Set a global variable in the global EL contexts. procedure Set_Global (App : in out Application; Name : in String; Value : in String); procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object); -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Get the list of supported locales for this application. function Get_Supported_Locales (App : in Application) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (App : in Application) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Handler : in Application; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Register a bundle and bind it to a facelet variable. procedure Register (App : in out Application; Name : in String; Bundle : in String); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (App : in out Application; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (App : in out Application; Name : in String; Class : in ASF.Beans.Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (App : in out Application; Name : in String; Handler : in ASF.Beans.Create_Bean_Access); -- Create a bean by using the create operation registered for the name procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type); -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. procedure Add_Converter (App : in out Application; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Register a binding library in the factory. procedure Add_Components (App : in out Application; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Closes the application procedure Close (App : in out Application); -- Set the current faces context before processing a view. procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access); -- Execute the lifecycle phases on the faces context. procedure Execute_Lifecycle (App : in Application; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Dispatch the request received on a page. procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Dispatch a bean action request. -- 1. Find the bean object identified by <b>Name</b>, create it if necessary. -- 2. Resolve the bean method identified by <b>Operation</b>. -- 3. If the method is an action method (see ASF.Events.Actions), call that method. -- 4. Using the outcome action result, decide using the navigation handler what -- is the result view. -- 5. Render the result view resolved by the navigation handler. procedure Dispatch (App : in out Application; Name : in String; Operation : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class)); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (App : in Application; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find_Validator (App : in Application; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Register some functions generic with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); procedure Register_Functions (App : in out Application'Class); -- Register some bean definitions. generic with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); procedure Register_Beans (App : in out Application'Class); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (App : in out Application; Name : in String; Locale : in String; Bundle : out ASF.Locales.Bundle); private type Application_Factory is tagged limited null record; type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with record View : aliased ASF.Applications.Views.View_Handler; Lifecycle : ASF.Lifecycles.Lifecycle_Access; Factory : aliased ASF.Beans.Bean_Factory; Locales : ASF.Locales.Factory; Globals : aliased EL.Variables.Default.Default_Variable_Mapper; Functions : aliased EL.Functions.Default.Default_Function_Mapper; -- The component factory Components : aliased ASF.Factory.Component_Factory; -- The action listener. Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access; -- The navigation handler. Navigation : ASF.Navigations.Navigation_Handler_Access := null; -- The permission manager. Permissions : Security.Policies.Policy_Manager_Access := null; end record; end ASF.Applications.Main;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Locales; with EL.Objects; with EL.Contexts; with EL.Functions; with EL.Functions.Default; with EL.Expressions; with EL.Variables.Default; with Ada.Strings.Unbounded; with ASF.Locales; with ASF.Factory; with ASF.Converters; with ASF.Validators; with ASF.Contexts.Faces; with ASF.Contexts.Exceptions; with ASF.Lifecycles; with ASF.Applications.Views; with ASF.Navigations; with ASF.Beans; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Events.Faces.Actions; with Security.Policies; use Security; with Security.OAuth.Servers; package ASF.Applications.Main is use ASF.Beans; -- ------------------------------ -- Factory for creation of lifecycle, view handler -- ------------------------------ type Application_Factory is tagged limited private; -- Create the lifecycle handler. The lifecycle handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object. -- It can be overriden to change the behavior of the ASF request lifecycle. function Create_Lifecycle_Handler (App : in Application_Factory) return ASF.Lifecycles.Lifecycle_Access; -- Create the view handler. The view handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Applications.Views.View_Handler</b> object. -- It can be overriden to change the views associated with the application. function Create_View_Handler (App : in Application_Factory) return ASF.Applications.Views.View_Handler_Access; -- Create the navigation handler. The navigation handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Navigations.Navigation_Handler</b> object. -- It can be overriden to change the navigations associated with the application. function Create_Navigation_Handler (App : in Application_Factory) return ASF.Navigations.Navigation_Handler_Access; -- Create the security policy manager. The security policy manager is created during -- the initialization phase of the application. The default implementation -- creates a <b>Security.Policies.Policy_Manager</b> object. function Create_Security_Manager (App : in Application_Factory) return Security.Policies.Policy_Manager_Access; -- Create the OAuth application manager. The OAuth application manager is created -- during the initialization phase of the application. The default implementation -- creates a <b>Security.OAuth.Servers.Auth_Manager</b> object. function Create_OAuth_Manager (App : in Application_Factory) return Security.OAuth.Servers.Auth_Manager_Access; -- Create the exception handler. The exception handler is created during -- the initialization phase of the application. The default implementation -- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object. function Create_Exception_Handler (App : in Application_Factory) return ASF.Contexts.Exceptions.Exception_Handler_Access; -- ------------------------------ -- Application -- ------------------------------ type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with private; type Application_Access is access all Application'Class; -- Get the application view handler. function Get_View_Handler (App : access Application) return access Views.View_Handler'Class; -- Get the lifecycle handler. function Get_Lifecycle_Handler (App : in Application) return ASF.Lifecycles.Lifecycle_Access; -- Get the navigation handler. function Get_Navigation_Handler (App : in Application) return ASF.Navigations.Navigation_Handler_Access; -- Get the permission manager associated with this application. function Get_Security_Manager (App : in Application) return Security.Policies.Policy_Manager_Access; -- Get the OAuth application manager associated with this application. function Get_OAuth_Manager (App : in Application) return Security.OAuth.Servers.Auth_Manager_Access; -- Get the action event listener responsible for processing action -- events and triggering the navigation to the next view using the -- navigation handler. function Get_Action_Listener (App : in Application) return ASF.Events.Faces.Actions.Action_Listener_Access; -- Process the action associated with the action event. The action returns -- and outcome which is then passed to the navigation handler to navigate to -- the next view. overriding procedure Process_Action (Listener : in Application; Event : in ASF.Events.Faces.Actions.Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class); -- Execute the action method. The action returns and outcome which is then passed -- to the navigation handler to navigate to the next view. procedure Process_Action (Listener : in Application; Method : in EL.Expressions.Method_Info; Context : in out Contexts.Faces.Faces_Context'Class); -- Initialize the application procedure Initialize (App : in out Application; Conf : in Config; Factory : in out Application_Factory'Class); -- 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. procedure Initialize_Components (App : in out Application); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. procedure Initialize_Config (App : in out Application; Conf : in out Config); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. procedure Initialize_Filters (App : in out Application); -- Finalizes the application, freeing the memory. overriding procedure Finalize (App : in out Application); -- Get the configuration parameter; function Get_Config (App : Application; Param : Config_Param) return String; -- Set a global variable in the global EL contexts. procedure Set_Global (App : in out Application; Name : in String; Value : in String); procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object); -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Get the list of supported locales for this application. function Get_Supported_Locales (App : in Application) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (App : in Application) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Handler : in Application; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Register a bundle and bind it to a facelet variable. procedure Register (App : in out Application; Name : in String; Bundle : in String); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (App : in out Application; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (App : in out Application; Name : in String; Class : in ASF.Beans.Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (App : in out Application; Name : in String; Handler : in ASF.Beans.Create_Bean_Access); -- Create a bean by using the create operation registered for the name procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type); -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. procedure Add_Converter (App : in out Application; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Register a binding library in the factory. procedure Add_Components (App : in out Application; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Closes the application procedure Close (App : in out Application); -- Set the current faces context before processing a view. procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access); -- Execute the lifecycle phases on the faces context. procedure Execute_Lifecycle (App : in Application; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Dispatch the request received on a page. procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Dispatch a bean action request. -- 1. Find the bean object identified by <b>Name</b>, create it if necessary. -- 2. Resolve the bean method identified by <b>Operation</b>. -- 3. If the method is an action method (see ASF.Events.Actions), call that method. -- 4. Using the outcome action result, decide using the navigation handler what -- is the result view. -- 5. Render the result view resolved by the navigation handler. procedure Dispatch (App : in out Application; Name : in String; Operation : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class)); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (App : in Application; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find_Validator (App : in Application; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Register some functions generic with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); procedure Register_Functions (App : in out Application'Class); -- Register some bean definitions. generic with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); procedure Register_Beans (App : in out Application'Class); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (App : in out Application; Name : in String; Locale : in String; Bundle : out ASF.Locales.Bundle); private type Application_Factory is tagged limited null record; type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with record View : aliased ASF.Applications.Views.View_Handler; Lifecycle : ASF.Lifecycles.Lifecycle_Access; Factory : aliased ASF.Beans.Bean_Factory; Locales : ASF.Locales.Factory; Globals : aliased EL.Variables.Default.Default_Variable_Mapper; Functions : aliased EL.Functions.Default.Default_Function_Mapper; -- The component factory Components : aliased ASF.Factory.Component_Factory; -- The action listener. Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access; -- The navigation handler. Navigation : ASF.Navigations.Navigation_Handler_Access; -- The permission manager. Permissions : Security.Policies.Policy_Manager_Access; -- The OAuth application manager. OAuth : Security.OAuth.Servers.Auth_Manager_Access; end record; end ASF.Applications.Main;
Declare the Get_OAuth_Manager function to retrieve the OAuth manager
Declare the Get_OAuth_Manager function to retrieve the OAuth manager
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
70f5453c6ccb4ae802f5977737d3528bcfe39adc
src/core/util-stacks.adb
src/core/util-stacks.adb
----------------------------------------------------------------------- -- util-stacks -- Simple stack -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Stacks is procedure Free is new Ada.Unchecked_Deallocation (Element_Type_Array, Element_Type_Array_Access); -- ------------------------------ -- Get access to the current stack element. -- ------------------------------ function Current (Container : in Stack) return Element_Type_Access is begin return Container.Current; end Current; -- ------------------------------ -- Push an element on top of the stack making the new element the current one. -- ------------------------------ procedure Push (Container : in out Stack) is begin if Container.Stack = null then Container.Stack := new Element_Type_Array (1 .. 100); Container.Pos := Container.Stack'First; elsif Container.Pos = Container.Stack'Last then declare Old : Element_Type_Array_Access := Container.Stack; begin Container.Stack := new Element_Type_Array (1 .. Old'Last + 100); Container.Stack (1 .. Old'Last) := Old (1 .. Old'Last); Free (Old); end; end if; if Container.Pos /= Container.Stack'First then Container.Stack (Container.Pos + 1) := Container.Stack (Container.Pos); end if; Container.Pos := Container.Pos + 1; Container.Current := Container.Stack (Container.Pos)'Access; end Push; -- ------------------------------ -- Pop the top element. -- ------------------------------ procedure Pop (Container : in out Stack) is begin Container.Pos := Container.Pos - 1; Container.Current := Container.Stack (Container.Pos)'Access; end Pop; -- ------------------------------ -- Clear the stack. -- ------------------------------ procedure Clear (Container : in out Stack) is begin if Container.Stack /= null then Container.Pos := Container.Stack'First; end if; Container.Current := null; end Clear; -- ------------------------------ -- Release the stack -- ------------------------------ overriding procedure Finalize (Obj : in out Stack) is begin Free (Obj.Stack); end Finalize; end Util.Stacks;
----------------------------------------------------------------------- -- util-stacks -- Simple stack -- Copyright (C) 2010, 2011, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Stacks is procedure Free is new Ada.Unchecked_Deallocation (Element_Type_Array, Element_Type_Array_Access); -- ------------------------------ -- Get access to the current stack element. -- ------------------------------ function Current (Container : in Stack) return Element_Type_Access is begin return Container.Current; end Current; -- ------------------------------ -- Push an element on top of the stack making the new element the current one. -- ------------------------------ procedure Push (Container : in out Stack) is begin if Container.Stack = null then Container.Stack := new Element_Type_Array (1 .. 100); Container.Pos := Container.Stack'First; elsif Container.Pos = Container.Stack'Last then declare Old : Element_Type_Array_Access := Container.Stack; begin Container.Stack := new Element_Type_Array (1 .. Old'Last + 100); Container.Stack (1 .. Old'Last) := Old (1 .. Old'Last); Free (Old); end; end if; if Container.Pos /= Container.Stack'First then Container.Stack (Container.Pos + 1) := Container.Stack (Container.Pos); end if; Container.Pos := Container.Pos + 1; Container.Current := Container.Stack (Container.Pos)'Access; end Push; -- ------------------------------ -- Pop the top element. -- ------------------------------ procedure Pop (Container : in out Stack) is begin if Container.Pos > Container.Stack'First then Container.Pos := Container.Pos - 1; Container.Current := Container.Stack (Container.Pos)'Access; else Container.Current := null; end if; end Pop; -- ------------------------------ -- Clear the stack. -- ------------------------------ procedure Clear (Container : in out Stack) is begin if Container.Stack /= null then Container.Pos := Container.Stack'First; end if; Container.Current := null; end Clear; -- ------------------------------ -- Returns true if the stack is empty. -- ------------------------------ function Is_Empty (Container : in out Stack) return Boolean is begin return Container.Stack = null or else Container.Pos = Container.Stack'First; end Is_Empty; -- ------------------------------ -- Release the stack -- ------------------------------ overriding procedure Finalize (Obj : in out Stack) is begin Free (Obj.Stack); end Finalize; end Util.Stacks;
Add Is_Empty function and fix Pop when the last element is popped
Add Is_Empty function and fix Pop when the last element is popped
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
785510de6dd86ac6568c7ef290dfe69a30d87b57
src/asf-servlets-faces.ads
src/asf-servlets-faces.ads
----------------------------------------------------------------------- -- asf.servlets.faces -- Faces 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 ASF.Applications.Main; package ASF.Servlets.Faces is -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Faces_Servlet is new Servlet with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Faces_Servlet; Context : in Servlet_Registry'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" procedure Do_Get (Server : in Faces_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a POST request. The HTTP POST method allows the client to send data of unlimited -- length to the Web server a single time and is useful when posting information -- such as credit card numbers. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. When using -- a PrintWriter object to return the response, set the content type before -- accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container to use -- a persistent connection to return its response to the client, improving -- performance. The content length is automatically set if the entire response -- fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- This method does not need to be either safe or idempotent. Operations -- requested through POST can have side effects for which the user can be held -- accountable, for example, updating stored data or buying items online. -- -- If the HTTP POST request is incorrectly formatted, doPost returns -- an HTTP "Bad Request" message. procedure Do_Post (Server : in Faces_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); private type Faces_Servlet is new Servlet with record App : ASF.Applications.Main.Application_Access; end record; end ASF.Servlets.Faces;
----------------------------------------------------------------------- -- asf.servlets.faces -- Faces servlet -- Copyright (C) 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Servlet.Core; with ASF.Requests; with ASF.Responses; with ASF.Applications.Main; package ASF.Servlets.Faces is -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Faces_Servlet is new Servlet.Core.Servlet with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Faces_Servlet; Context : in Servlet_Registry'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" procedure Do_Get (Server : in Faces_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a POST request. The HTTP POST method allows the client to send data of unlimited -- length to the Web server a single time and is useful when posting information -- such as credit card numbers. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. When using -- a PrintWriter object to return the response, set the content type before -- accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container to use -- a persistent connection to return its response to the client, improving -- performance. The content length is automatically set if the entire response -- fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- This method does not need to be either safe or idempotent. Operations -- requested through POST can have side effects for which the user can be held -- accountable, for example, updating stored data or buying items online. -- -- If the HTTP POST request is incorrectly formatted, doPost returns -- an HTTP "Bad Request" message. procedure Do_Post (Server : in Faces_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); private type Faces_Servlet is new Servlet.Core.Servlet with record App : ASF.Applications.Main.Application_Access; end record; end ASF.Servlets.Faces;
Package ASF.Servlets moved to Servlet.Core
Package ASF.Servlets moved to Servlet.Core
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c2332657b015abafdcd24ba535a7abcf9420a942
src/gen-model-packages.ads
src/gen-model-packages.ads
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Strings.Sets; with Gen.Model.List; with Gen.Model.Mappings; limited with Gen.Model.Enums; limited with Gen.Model.Tables; limited with Gen.Model.Queries; limited with Gen.Model.Beans; package Gen.Model.Packages is use Ada.Strings.Unbounded; -- ------------------------------ -- Model Definition -- ------------------------------ -- The <b>Model_Definition</b> contains the complete model from one or -- several files. It maintains a list of Ada packages that must be generated. type Model_Definition is new Definition with private; type Model_Definition_Access is access all Model_Definition'Class; -- ------------------------------ -- Package Definition -- ------------------------------ -- The <b>Package_Definition</b> holds the tables, queries and other information -- that must be generated for a given Ada package. type Package_Definition is new Definition with private; type Package_Definition_Access is access all Package_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Package_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Package_Definition); -- Initialize the package instance overriding procedure Initialize (O : in out Package_Definition); -- Find the type identified by the name. function Find_Type (From : in Package_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Get the model which contains all the package definitions. function Get_Model (From : in Package_Definition) return Model_Definition_Access; -- Returns True if the package is a pre-defined package and must not be generated. function Is_Predefined (From : in Package_Definition) return Boolean; -- Set the package as a pre-defined package. procedure Set_Predefined (From : in out Package_Definition); -- 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 : Model_Definition; Name : String) return Util.Beans.Objects.Object; -- Initialize the model definition instance. overriding procedure Initialize (O : in out Model_Definition); -- Returns True if the model contains at least one package. function Has_Packages (O : in Model_Definition) return Boolean; -- Register or find the package knowing its name procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access); -- Register the declaration of the given enum in the model. procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class); -- Register the declaration of the given table in the model. procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class); -- Register the declaration of the given query in the model. procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_File_Definition'Class); -- Register the declaration of the given bean in the model. procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class); -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. procedure Register_Type (O : in out Model_Definition; From : in String; To : in String); -- Find the type identified by the name. function Find_Type (From : in Model_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String); -- Get the directory name associated with the model. function Get_Dirname (O : in Model_Definition) return String; -- Get the directory name which contains the model. function Get_Model_Directory (O : in Model_Definition) return String; -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (Model : in out Model_Definition; Name : in String); -- Returns True if the generation is enabled for the given package name. function Is_Generation_Enabled (Model : in Model_Definition; Name : in String) return Boolean; -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Model_Definition); package Package_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Package_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Package_Cursor is Package_Map.Cursor; -- Get the first package of the model definition. function First (From : Model_Definition) return Package_Cursor; -- Returns true if the package cursor contains a valid package function Has_Element (Position : Package_Cursor) return Boolean renames Package_Map.Has_Element; -- Returns the package definition. function Element (Position : Package_Cursor) return Package_Definition_Access renames Package_Map.Element; -- Move the iterator to the next package definition. procedure Next (Position : in out Package_Cursor) renames Package_Map.Next; private package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); -- Returns False if the <tt>Left</tt> table does not depend on <tt>Right</tt>. -- Returns True if the <tt>Left</tt> table depends on the <tt>Right</tt> table. function Dependency_Compare (Left, Right : in Definition_Access) return Boolean; -- Sort the tables on their dependency. procedure Dependency_Sort is new Table_List.Sort_On ("<" => Dependency_Compare); subtype Table_List_Definition is Table_List.List_Definition; subtype Enum_List_Definition is Table_List.List_Definition; type List_Object is new Util.Beans.Basic.List_Bean with record Values : Util.Beans.Objects.Vectors.Vector; Row : Natural; Value_Bean : Util.Beans.Objects.Object; end record; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Object) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Object) return Util.Beans.Objects.Object; -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object; type Package_Definition is new Definition with record -- Enums defined in the package. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- Hibernate tables Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- Custom queries Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Spec_Types : aliased List_Object; Used_Spec : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Body_Types : aliased List_Object; Used_Body : Util.Beans.Objects.Object; -- A map of all types defined in this package. Types : Gen.Model.Mappings.Mapping_Maps.Map; -- The base name for the package (ex: gen-model-users) Base_Name : Unbounded_String; -- The global model (used to resolve types from other packages). Model : Model_Definition_Access; -- True if the package uses Ada.Calendar.Time Uses_Calendar_Time : Boolean := False; -- True if the package is a pre-defined package (ie, defined by a UML profile). Is_Predefined : Boolean := False; end record; type Model_Definition is new Definition with record -- List of all enums. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- List of all tables. Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- List of all queries. Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- Map of all packages. Packages : Package_Map.Map; -- Directory associated with the model ('src', 'samples', 'regtests', ...). Dir_Name : Unbounded_String; -- Directory that contains the SQL and model files. DB_Name : Unbounded_String; -- When not empty, a list of packages that must be taken into account for the generation. -- By default all packages and tables defined in the model are generated. Gen_Packages : Util.Strings.Sets.Set; end record; end Gen.Model.Packages;
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Strings.Sets; with Gen.Model.List; with Gen.Model.Mappings; limited with Gen.Model.Enums; limited with Gen.Model.Tables; limited with Gen.Model.Queries; limited with Gen.Model.Beans; package Gen.Model.Packages is use Ada.Strings.Unbounded; -- ------------------------------ -- Model Definition -- ------------------------------ -- The <b>Model_Definition</b> contains the complete model from one or -- several files. It maintains a list of Ada packages that must be generated. type Model_Definition is new Definition with private; type Model_Definition_Access is access all Model_Definition'Class; -- ------------------------------ -- Package Definition -- ------------------------------ -- The <b>Package_Definition</b> holds the tables, queries and other information -- that must be generated for a given Ada package. type Package_Definition is new Definition with private; type Package_Definition_Access is access all Package_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Package_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Package_Definition); -- Initialize the package instance overriding procedure Initialize (O : in out Package_Definition); -- Find the type identified by the name. function Find_Type (From : in Package_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Get the model which contains all the package definitions. function Get_Model (From : in Package_Definition) return Model_Definition_Access; -- Returns True if the package is a pre-defined package and must not be generated. function Is_Predefined (From : in Package_Definition) return Boolean; -- Set the package as a pre-defined package. procedure Set_Predefined (From : in out Package_Definition); -- 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 : Model_Definition; Name : String) return Util.Beans.Objects.Object; -- Initialize the model definition instance. overriding procedure Initialize (O : in out Model_Definition); -- Returns True if the model contains at least one package. function Has_Packages (O : in Model_Definition) return Boolean; -- Register or find the package knowing its name procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access); -- Register the declaration of the given enum in the model. procedure Register_Enum (O : in out Model_Definition; Enum : access Gen.Model.Enums.Enum_Definition'Class); -- Register the declaration of the given table in the model. procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class); -- Register the declaration of the given query in the model. procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_File_Definition'Class); -- Register the declaration of the given bean in the model. procedure Register_Bean (O : in out Model_Definition; Bean : access Gen.Model.Beans.Bean_Definition'Class); -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. procedure Register_Type (O : in out Model_Definition; From : in String; To : in String); -- Find the type identified by the name. function Find_Type (From : in Model_Definition; Name : in Unbounded_String) return Gen.Model.Mappings.Mapping_Definition_Access; -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String); -- Get the directory name associated with the model. function Get_Dirname (O : in Model_Definition) return String; -- Get the directory name which contains the model. function Get_Model_Directory (O : in Model_Definition) return String; -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (Model : in out Model_Definition; Name : in String); -- Returns True if the generation is enabled for the given package name. function Is_Generation_Enabled (Model : in Model_Definition; Name : in String) return Boolean; -- Iterate over the model tables. procedure Iterate_Tables (Model : in Model_Definition; Process : not null access procedure (Item : in out Tables.Table_Definition)); -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. overriding procedure Prepare (O : in out Model_Definition); package Package_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Package_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Package_Cursor is Package_Map.Cursor; -- Get the first package of the model definition. function First (From : Model_Definition) return Package_Cursor; -- Returns true if the package cursor contains a valid package function Has_Element (Position : Package_Cursor) return Boolean renames Package_Map.Has_Element; -- Returns the package definition. function Element (Position : Package_Cursor) return Package_Definition_Access renames Package_Map.Element; -- Move the iterator to the next package definition. procedure Next (Position : in out Package_Cursor) renames Package_Map.Next; private package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); -- Returns False if the <tt>Left</tt> table does not depend on <tt>Right</tt>. -- Returns True if the <tt>Left</tt> table depends on the <tt>Right</tt> table. function Dependency_Compare (Left, Right : in Definition_Access) return Boolean; -- Sort the tables on their dependency. procedure Dependency_Sort is new Table_List.Sort_On ("<" => Dependency_Compare); subtype Table_List_Definition is Table_List.List_Definition; subtype Enum_List_Definition is Table_List.List_Definition; type List_Object is new Util.Beans.Basic.List_Bean with record Values : Util.Beans.Objects.Vectors.Vector; Row : Natural; Value_Bean : Util.Beans.Objects.Object; end record; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Object) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Object) return Util.Beans.Objects.Object; -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object; type Package_Definition is new Definition with record -- Enums defined in the package. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- Hibernate tables Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- Custom queries Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Spec_Types : aliased List_Object; Used_Spec : Util.Beans.Objects.Object; -- A list of external packages which are used (used for with clause generation). Used_Body_Types : aliased List_Object; Used_Body : Util.Beans.Objects.Object; -- A map of all types defined in this package. Types : Gen.Model.Mappings.Mapping_Maps.Map; -- The base name for the package (ex: gen-model-users) Base_Name : Unbounded_String; -- The global model (used to resolve types from other packages). Model : Model_Definition_Access; -- True if the package uses Ada.Calendar.Time Uses_Calendar_Time : Boolean := False; -- True if the package is a pre-defined package (ie, defined by a UML profile). Is_Predefined : Boolean := False; end record; type Model_Definition is new Definition with record -- List of all enums. Enums : aliased Enum_List_Definition; Enums_Bean : Util.Beans.Objects.Object; -- List of all tables. Tables : aliased Table_List_Definition; Tables_Bean : Util.Beans.Objects.Object; -- List of all queries. Queries : aliased Table_List_Definition; Queries_Bean : Util.Beans.Objects.Object; -- Ada Beans Beans : aliased Table_List_Definition; Beans_Bean : Util.Beans.Objects.Object; -- Map of all packages. Packages : Package_Map.Map; -- Directory associated with the model ('src', 'samples', 'regtests', ...). Dir_Name : Unbounded_String; -- Directory that contains the SQL and model files. DB_Name : Unbounded_String; -- When not empty, a list of packages that must be taken into account for the generation. -- By default all packages and tables defined in the model are generated. Gen_Packages : Util.Strings.Sets.Set; end record; end Gen.Model.Packages;
Declare the Iterate_Tables procedure to iterate easily over the model tables
Declare the Iterate_Tables procedure to iterate easily over the model tables
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
289abd3e5c63aa1d9a9c2fdc573b83241cc71632
mat/src/mat-types.ads
mat/src/mat-types.ads
----------------------------------------------------------------------- -- mat-types -- Global types -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; package MAT.Types is type String_Ptr is access all String; subtype Uint8 is Interfaces.Unsigned_8; subtype Uint16 is Interfaces.Unsigned_16; subtype Uint32 is Interfaces.Unsigned_32; subtype Uint64 is Interfaces.Unsigned_64; subtype Target_Addr is Interfaces.Unsigned_32; subtype Target_Size is Interfaces.Unsigned_32; subtype Target_Offset is Interfaces.Unsigned_32; subtype Target_Tick_Ref is Uint64; subtype Target_Thread_Ref is Uint32; subtype Target_Time is Uint64; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String; end MAT.Types;
----------------------------------------------------------------------- -- mat-types -- Global types -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; package MAT.Types is type String_Ptr is access all String; subtype Uint8 is Interfaces.Unsigned_8; subtype Uint16 is Interfaces.Unsigned_16; subtype Uint32 is Interfaces.Unsigned_32; subtype Uint64 is Interfaces.Unsigned_64; subtype Target_Addr is Interfaces.Unsigned_32; subtype Target_Size is Interfaces.Unsigned_32; subtype Target_Offset is Interfaces.Unsigned_32; subtype Target_Tick_Ref is Uint64; subtype Target_Thread_Ref is Uint32; subtype Target_Process_Ref is Uint32; subtype Target_Time is Uint64; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String; end MAT.Types;
Declare Target_Process_Ref type
Declare Target_Process_Ref type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
901742191fc35774d3bd63f194934b47ea4aabef
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Util.Strings; with Wiki.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End, Underline_Start, Underline_End, Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Preformat_Start, Preformat_End, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; Invert_Header_Level : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Documents; with Wiki.Attributes; with Wiki.Writers; with Wiki.Parsers; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Standard.Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Wiki_Renderer; Writer : in Writers.Writer_Type_Access; Format : in Parsers.Wiki_Syntax_Type); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Wiki_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Wiki_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Wiki_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Wiki_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Wiki_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Attribute_List_Type); overriding procedure End_Element (Document : in out Wiki_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Wiki_Renderer); private type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Bold_Start, Bold_End, Italic_Start, Italic_End, Underline_Start, Underline_End, Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Preformat_Start, Preformat_End, Line_Break, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Document : in out Wiki_Renderer); procedure Close_Paragraph (Document : in out Wiki_Renderer); procedure Open_Paragraph (Document : in out Wiki_Renderer); procedure Start_Keep_Content (Document : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Documents.Document_Reader with record Writer : Writers.Writer_Type_Access := null; Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE; Format : Documents.Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; Invert_Header_Level : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; Current_Style : Documents.Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
616830343c34afd818134f5801fd91c47f217207
awa/src/awa-components-wikis.ads
awa/src/awa-components-wikis.ads
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ASF.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Strings; with Wiki.Render; with Wiki.Plugins; with Wiki.Render.Links; package AWA.Components.Wikis is use ASF.Contexts.Faces; -- The wiki format of the wiki text. The valid values are: -- dotclear, google, creole, phpbb, mediawiki FORMAT_NAME : constant String := "format"; VALUE_NAME : constant String := ASF.Components.VALUE_NAME; -- The link renderer bean that controls the generation of page and image links. LINKS_NAME : constant String := "links"; -- The plugin factory bean that must be used for Wiki plugins. PLUGINS_NAME : constant String := "plugins"; -- Whether the TOC is rendered in the document. TOC_NAME : constant String := "toc"; -- ------------------------------ -- Wiki component -- ------------------------------ -- -- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/> -- type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record; type UIWiki_Access is access all UIWiki'Class; -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax; -- Get the links renderer that must be used to render image and page links. function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access; -- Get the plugin factory that must be used by the Wiki parser. function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); use Ada.Strings.Wide_Wide_Unbounded; IMAGE_PREFIX_ATTR : constant String := "image_prefix"; PAGE_PREFIX_ATTR : constant String := "page_prefix"; type Link_Renderer_Bean is new Util.Beans.Basic.Bean and Wiki.Render.Links.Link_Renderer with record Page_Prefix : Unbounded_Wide_Wide_String; Image_Prefix : Unbounded_Wide_Wide_String; end record; -- Make a link adding a prefix unless the link is already absolute. procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String); -- Get the value identified by the name. overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); private function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean; end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ASF.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Strings; with Wiki.Render; with Wiki.Plugins; with Wiki.Render.Links; package AWA.Components.Wikis is use ASF.Contexts.Faces; -- The wiki format of the wiki text. The valid values are: -- dotclear, google, creole, phpbb, mediawiki FORMAT_NAME : constant String := "format"; VALUE_NAME : constant String := ASF.Components.VALUE_NAME; -- The link renderer bean that controls the generation of page and image links. LINKS_NAME : constant String := "links"; -- The plugin factory bean that must be used for Wiki plugins. PLUGINS_NAME : constant String := "plugins"; -- Whether the TOC is rendered in the document. TOC_NAME : constant String := "toc"; -- ------------------------------ -- Wiki component -- ------------------------------ -- -- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/> -- type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record; type UIWiki_Access is access all UIWiki'Class; -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax; -- Get the links renderer that must be used to render image and page links. function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access; -- Get the plugin factory that must be used by the Wiki parser. function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); use Ada.Strings.Wide_Wide_Unbounded; IMAGE_PREFIX_ATTR : constant String := "image_prefix"; PAGE_PREFIX_ATTR : constant String := "page_prefix"; type Link_Renderer_Bean is new Util.Beans.Basic.Bean and Wiki.Render.Links.Link_Renderer with record Page_Prefix : Unbounded_Wide_Wide_String; Image_Prefix : Unbounded_Wide_Wide_String; end record; -- Make a link adding a prefix unless the link is already absolute. procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String); -- Get the value identified by the name. overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); private function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean; end AWA.Components.Wikis;
Change Make_Image_Link procedure to use in out parameter for Width and Height
Change Make_Image_Link procedure to use in out parameter for Width and Height
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3640375282cfaed0ed828ab65b08b3b9d2b71fae
awa/src/awa-components-wikis.adb
awa/src/awa-components-wikis.adb
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 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.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Documents; with Wiki.Parsers; with Wiki.Helpers; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Filters.Autolink; with Wiki.Filters.Variables; with Wiki.Streams.Html; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then return Wiki.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.SYNTAX_CREOLE; elsif Format = "markdown" or Format = "FORMAT_MARKDOWN" then return Wiki.SYNTAX_MARKDOWN; elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; elsif Format = "html" or Format = "FORMAT_HTML" then return Wiki.SYNTAX_HTML; else return Wiki.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Get the links renderer that must be used to render image and page links. -- ------------------------------ function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Get the plugin factory that must be used by the Wiki parser. -- ------------------------------ function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, PLUGINS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Wiki.Plugins.Plugin_Factory'Class) then return null; else return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access; end if; end Get_Plugin_Factory; -- ------------------------------ -- Returns true if we must render a text content instead of html. -- ------------------------------ function Is_Text (UI : in UIWiki; Context : in Faces_Context'Class) return Boolean is use type Util.Beans.Objects.Object; Output : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, OUTPUT_NAME); begin if Util.Beans.Objects.Is_Null (Output) then return False; end if; return Output = Util.Beans.Objects.To_Object (String '("text")); end Is_Text; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Links.Link_Renderer_Access; use type Wiki.Plugins.Plugin_Factory_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Vars : aliased Wiki.Filters.Variables.Variable_Filter; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Is_Text : constant Boolean := UI.Is_Text (Context); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin if not Is_Text then Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); end if; if not Util.Beans.Objects.Is_Empty (Value) then Plugins := UI.Get_Plugin_Factory (Context); if Plugins /= null then Engine.Set_Plugin_Factory (Plugins); end if; Links := UI.Get_Links_Renderer (Context); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Vars'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_String (Value), Doc); if not Is_Text then declare Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Html.Writer := Writer; if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Set_Render_TOC (UI.Get_Attribute (TOC_NAME, Context, False)); Renderer.Render (Doc); end; else declare Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Html.Writer := Writer; Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Render (Doc); end; end if; end if; if not Is_Text then Writer.End_Element ("div"); end if; end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); 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 Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is pragma Unreferenced (Renderer); begin if Wiki.Helpers.Is_Url (Link) then URI := To_Unbounded_Wide_Wide_String (Link); else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Documents; with Wiki.Parsers; with Wiki.Helpers; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Filters.Autolink; with Wiki.Filters.Variables; with Wiki.Streams.Html; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then return Wiki.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.SYNTAX_CREOLE; elsif Format = "markdown" or Format = "FORMAT_MARKDOWN" then return Wiki.SYNTAX_MARKDOWN; elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; elsif Format = "html" or Format = "FORMAT_HTML" then return Wiki.SYNTAX_HTML; else return Wiki.SYNTAX_MARKDOWN; end if; end Get_Wiki_Style; -- ------------------------------ -- Get the links renderer that must be used to render image and page links. -- ------------------------------ function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Get the plugin factory that must be used by the Wiki parser. -- ------------------------------ function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, PLUGINS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Wiki.Plugins.Plugin_Factory'Class) then return null; else return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access; end if; end Get_Plugin_Factory; -- ------------------------------ -- Returns true if we must render a text content instead of html. -- ------------------------------ function Is_Text (UI : in UIWiki; Context : in Faces_Context'Class) return Boolean is use type Util.Beans.Objects.Object; Output : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, OUTPUT_NAME); begin if Util.Beans.Objects.Is_Null (Output) then return False; end if; return Output = Util.Beans.Objects.To_Object (String '("text")); end Is_Text; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Links.Link_Renderer_Access; use type Wiki.Plugins.Plugin_Factory_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Vars : aliased Wiki.Filters.Variables.Variable_Filter; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Is_Text : constant Boolean := UI.Is_Text (Context); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin if not Is_Text then Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); end if; if not Util.Beans.Objects.Is_Empty (Value) then Plugins := UI.Get_Plugin_Factory (Context); if Plugins /= null then Engine.Set_Plugin_Factory (Plugins); end if; Links := UI.Get_Links_Renderer (Context); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Vars'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_String (Value), Doc); if not Is_Text then declare Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Html.Writer := Writer; if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Set_Render_TOC (UI.Get_Attribute (TOC_NAME, Context, False)); Renderer.Render (Doc); end; else declare Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Html.Writer := Writer; Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Render (Doc); end; end if; end if; if not Is_Text then Writer.End_Element ("div"); end if; end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); 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 Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is pragma Unreferenced (Renderer); begin if Wiki.Helpers.Is_Url (Link) then URI := To_Unbounded_Wide_Wide_String (Link); else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
Replace SYNTAX_MIX by SYNTAX_MARKDOWN
Replace SYNTAX_MIX by SYNTAX_MARKDOWN
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
50212ef4cf6496cf3444deda10554955b86534df
src/wiki-strings.ads
src/wiki-strings.ads
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
Declare the Element function
Declare the Element function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f9cd7b181db55a7ef46d19007385329d6f46fd5c
src/gen-model-beans.ads
src/gen-model-beans.ads
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Bean Definition -- ------------------------------ type Bean_Definition is new Tables.Table_Definition with null record; type Bean_Definition_Access is access all Bean_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Bean_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Bean_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Bean_Definition); -- Create an attribute with the given name and add it to the bean. procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access); -- Create a bean with the given name. function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access; end Gen.Model.Beans;
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.Tables; with Gen.Model.Operations; package Gen.Model.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Bean Definition -- ------------------------------ type Bean_Definition is new Tables.Table_Definition with null record; type Bean_Definition_Access is access all Bean_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Bean_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Bean_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Bean_Definition); -- Create an attribute with the given name and add it to the bean. procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access); -- Create a bean with the given name. function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access; end Gen.Model.Beans;
Use the operations model
Use the operations model
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d56e6a0836a9e9fbfb61c652751d543ac38f55f2
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 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; with AWA.Helpers.Selectors; 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")); declare DB : ADO.Sessions.Master_Session := App.Get_Master_Session; begin App.Events.Initialize (DB); end; AWA.Modules.Initialize (App.Modules, Conf); App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean", AWA.Helpers.Selectors.Create_Select_List_Bean'Access); end Initialize_Config; -- ------------------------------ -- Initialize the 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; -- ------------------------------ -- Send the event in the application event queues. -- ------------------------------ procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class) is begin App.Events.Send (Event); end Send_Event; end AWA.Applications;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; 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; with AWA.Helpers.Selectors; 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")); declare DB : ADO.Sessions.Master_Session := App.Get_Master_Session; begin App.Events.Initialize (DB); end; AWA.Modules.Initialize (App.Modules, Conf); App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean", AWA.Helpers.Selectors.Create_Select_List_Bean'Access); end Initialize_Config; -- ------------------------------ -- Initialize the 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 begin AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); end Register; -- ------------------------------ -- Send the event in the application event queues. -- ------------------------------ procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class) is begin App.Events.Send (Event); end Send_Event; end AWA.Applications;
Remove unused commented code
Remove unused commented code
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
bbf31db0e69fd55dcde47ef4082e301f0d3a5429
src/postgresql/ado-drivers-connections-postgresql.ads
src/postgresql/ado-drivers-connections-postgresql.ads
----------------------------------------------------------------------- -- ADO Postgresql Database -- Postgresql Database connections -- 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. ----------------------------------------------------------------------- private with PQ; package ADO.Drivers.Connections.Postgresql is type Postgresql_Driver is limited private; -- Initialize the Postgresql driver. procedure Initialize; private -- Create a new Postgresql connection using the configuration parameters. procedure Create_Connection (D : in out Postgresql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); type Postgresql_Driver is new ADO.Drivers.Connections.Driver with record Id : Natural := 0; end record; -- Deletes the Postgresql driver. overriding procedure Finalize (D : in out Postgresql_Driver); -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Name : Unbounded_String; Server_Name : Unbounded_String; Login_Name : Unbounded_String; Password : Unbounded_String; Server : PQ.PGconn_Access := PQ.Null_PGconn; Connected : Boolean := False; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); overriding procedure Finalize (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); end ADO.Drivers.Connections.Postgresql;
----------------------------------------------------------------------- -- ADO Postgresql Database -- Postgresql Database connections -- 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. ----------------------------------------------------------------------- private with PQ; package ADO.Drivers.Connections.Postgresql is type Postgresql_Driver is limited private; -- Initialize the Postgresql driver. procedure Initialize; private -- Create a new Postgresql connection using the configuration parameters. procedure Create_Connection (D : in out Postgresql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); type Postgresql_Driver is new ADO.Drivers.Connections.Driver with record Id : Natural := 0; end record; -- Deletes the Postgresql driver. overriding procedure Finalize (D : in out Postgresql_Driver); -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Name : Unbounded_String; Server_Name : Unbounded_String; Login_Name : Unbounded_String; Password : Unbounded_String; Server : PQ.PGconn_Access := PQ.Null_PGconn; Connected : Boolean := False; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); overriding procedure Finalize (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Create the database and initialize it with the schema SQL file. overriding procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); end ADO.Drivers.Connections.Postgresql;
Declare the Create_Database procedure
Declare the Create_Database procedure
Ada
apache-2.0
stcarrez/ada-ado
269f1cc79a75eb67e773b9fb1c7c7f8ec7f1cf19
src/asf-sessions.adb
src/asf-sessions.adb
----------------------------------------------------------------------- -- asf.sessions -- ASF Sessions -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; -- The <b>ASF.Sessions</b> package is an Ada implementation of the -- Java servlet Specification (See JSR 315 at jcp.org). package body ASF.Sessions is use Ada.Strings.Unbounded; -- ------------------------------ -- Returns true if the session is valid. -- ------------------------------ function Is_Valid (Sess : in Session'Class) return Boolean is begin return Sess.Impl /= null and then Sess.Impl.Is_Active; end Is_Valid; -- ------------------------------ -- Returns a string containing the unique identifier assigned to this session. -- The identifier is assigned by the servlet container and is implementation dependent. -- ------------------------------ function Get_Id (Sess : in Session) return String is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Id.all; end if; end Get_Id; -- ------------------------------ -- Returns the last time the client sent a request associated with this session, -- as the number of milliseconds since midnight January 1, 1970 GMT, and marked -- by the time the container recieved the request. -- -- Actions that your application takes, such as getting or setting a value associated -- with the session, do not affect the access time. -- ------------------------------ function Get_Last_Accessed_Time (Sess : in Session) return Ada.Calendar.Time is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Access_Time; end if; end Get_Last_Accessed_Time; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Sess : in Session) return Duration is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Max_Inactive; end if; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Sess : in Session; Interval : in Duration) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else Sess.Impl.Max_Inactive := Interval; end if; end Set_Max_Inactive_Interval; -- ------------------------------ -- Returns the object bound with the specified name in this session, -- or null if no object is bound under the name. -- ------------------------------ function Get_Attribute (Sess : in Session; Name : in String) return EL.Objects.Object is Key : constant Unbounded_String := To_Unbounded_String (Name); begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Lock.Read; declare Pos : constant EL.Objects.Maps.Cursor := Sess.Impl.Attributes.Find (Key); begin if EL.Objects.Maps.Has_Element (Pos) then return Value : constant EL.Objects.Object := EL.Objects.Maps.Element (Pos) do Sess.Impl.Lock.Release_Read; end return; end if; exception when others => Sess.Impl.Lock.Release_Read; raise; end; Sess.Impl.Lock.Release_Read; return EL.Objects.Null_Object; end Get_Attribute; -- ------------------------------ -- Binds an object to this session, using the name specified. -- If an object of the same name is already bound to the session, -- the object is replaced. -- -- If the value passed in is null, this has the same effect as calling -- removeAttribute(). -- ------------------------------ procedure Set_Attribute (Sess : in out Session; Name : in String; Value : in EL.Objects.Object) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; declare Key : constant Unbounded_String := To_Unbounded_String (Name); begin Sess.Impl.Lock.Write; if EL.Objects.Is_Null (Value) then Sess.Impl.Attributes.Delete (Key); else Sess.Impl.Attributes.Include (Key, Value); end if; exception when others => Sess.Impl.Lock.Release_Write; raise; end; Sess.Impl.Lock.Release_Write; end Set_Attribute; -- ------------------------------ -- Removes the object bound with the specified name from this session. -- If the session does not have an object bound with the specified name, -- this method does nothing. -- ------------------------------ procedure Remove_Attribute (Sess : in out Session; Name : in String) is begin Set_Attribute (Sess, Name, EL.Objects.Null_Object); end Remove_Attribute; -- ------------------------------ -- Gets the principal that authenticated to the session. -- Returns null if there is no principal authenticated. -- ------------------------------ function Get_Principal (Sess : in Session) return ASF.Principals.Principal_Access is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; return Sess.Impl.Principal; end Get_Principal; -- ------------------------------ -- Sets the principal associated with the session. -- ------------------------------ procedure Set_Principal (Sess : in out Session; Principal : in ASF.Principals.Principal_Access) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Principal := Principal; end Set_Principal; -- ------------------------------ -- Invalidates this session then unbinds any objects bound to it. -- ------------------------------ procedure Invalidate (Sess : in out Session) is begin if Sess.Impl /= null then Sess.Impl.Is_Active := False; Finalize (Sess); end if; end Invalidate; -- ------------------------------ -- Adjust (increment) the session record reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Ref_Counter); end if; end Adjust; procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record'Class, Name => Session_Record_Access); -- ------------------------------ -- Decrement the session record reference counter and free the session record -- if this was the last session reference. -- ------------------------------ overriding procedure Finalize (Object : in out Session) is Release : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Ref_Counter, Release); if Release then Free (Object.Impl); else Object.Impl := null; end if; end if; end Finalize; overriding procedure Finalize (Object : in out Session_Record) is begin Free (Object.Id); end Finalize; end ASF.Sessions;
----------------------------------------------------------------------- -- asf.sessions -- ASF Sessions -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; -- The <b>ASF.Sessions</b> package is an Ada implementation of the -- Java servlet Specification (See JSR 315 at jcp.org). package body ASF.Sessions is use Ada.Strings.Unbounded; -- ------------------------------ -- Returns true if the session is valid. -- ------------------------------ function Is_Valid (Sess : in Session'Class) return Boolean is begin return Sess.Impl /= null and then Sess.Impl.Is_Active; end Is_Valid; -- ------------------------------ -- Returns a string containing the unique identifier assigned to this session. -- The identifier is assigned by the servlet container and is implementation dependent. -- ------------------------------ function Get_Id (Sess : in Session) return String is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Id.all; end if; end Get_Id; -- ------------------------------ -- Returns the last time the client sent a request associated with this session, -- as the number of milliseconds since midnight January 1, 1970 GMT, and marked -- by the time the container recieved the request. -- -- Actions that your application takes, such as getting or setting a value associated -- with the session, do not affect the access time. -- ------------------------------ function Get_Last_Accessed_Time (Sess : in Session) return Ada.Calendar.Time is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Access_Time; end if; end Get_Last_Accessed_Time; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Sess : in Session) return Duration is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Max_Inactive; end if; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Sess : in Session; Interval : in Duration) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else Sess.Impl.Max_Inactive := Interval; end if; end Set_Max_Inactive_Interval; -- ------------------------------ -- Returns the object bound with the specified name in this session, -- or null if no object is bound under the name. -- ------------------------------ function Get_Attribute (Sess : in Session; Name : in String) return EL.Objects.Object is Key : constant Unbounded_String := To_Unbounded_String (Name); begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Lock.Read; declare Pos : constant EL.Objects.Maps.Cursor := Sess.Impl.Attributes.Find (Key); begin if EL.Objects.Maps.Has_Element (Pos) then return Value : constant EL.Objects.Object := EL.Objects.Maps.Element (Pos) do Sess.Impl.Lock.Release_Read; end return; end if; exception when others => Sess.Impl.Lock.Release_Read; raise; end; Sess.Impl.Lock.Release_Read; return EL.Objects.Null_Object; end Get_Attribute; -- ------------------------------ -- Binds an object to this session, using the name specified. -- If an object of the same name is already bound to the session, -- the object is replaced. -- -- If the value passed in is null, this has the same effect as calling -- removeAttribute(). -- ------------------------------ procedure Set_Attribute (Sess : in out Session; Name : in String; Value : in EL.Objects.Object) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; declare Key : constant Unbounded_String := To_Unbounded_String (Name); begin Sess.Impl.Lock.Write; if EL.Objects.Is_Null (Value) then Sess.Impl.Attributes.Delete (Key); else Sess.Impl.Attributes.Include (Key, Value); end if; exception when others => Sess.Impl.Lock.Release_Write; raise; end; Sess.Impl.Lock.Release_Write; end Set_Attribute; -- ------------------------------ -- Removes the object bound with the specified name from this session. -- If the session does not have an object bound with the specified name, -- this method does nothing. -- ------------------------------ procedure Remove_Attribute (Sess : in out Session; Name : in String) is begin Set_Attribute (Sess, Name, EL.Objects.Null_Object); end Remove_Attribute; -- ------------------------------ -- Gets the principal that authenticated to the session. -- Returns null if there is no principal authenticated. -- ------------------------------ function Get_Principal (Sess : in Session) return ASF.Principals.Principal_Access is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; return Sess.Impl.Principal; end Get_Principal; -- ------------------------------ -- Sets the principal associated with the session. -- ------------------------------ procedure Set_Principal (Sess : in out Session; Principal : in ASF.Principals.Principal_Access) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Principal := Principal; end Set_Principal; -- ------------------------------ -- Invalidates this session then unbinds any objects bound to it. -- ------------------------------ procedure Invalidate (Sess : in out Session) is begin if Sess.Impl /= null then Sess.Impl.Is_Active := False; Finalize (Sess); end if; end Invalidate; -- ------------------------------ -- Adjust (increment) the session record reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Ref_Counter); end if; end Adjust; procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record'Class, Name => Session_Record_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Principals.Principal'Class, Name => ASF.Principals.Principal_Access); -- ------------------------------ -- Decrement the session record reference counter and free the session record -- if this was the last session reference. -- ------------------------------ overriding procedure Finalize (Object : in out Session) is Release : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Ref_Counter, Release); if Release then Free (Object.Impl.Principal); Free (Object.Impl); else Object.Impl := null; end if; end if; end Finalize; overriding procedure Finalize (Object : in out Session_Record) is begin Free (Object.Id); end Finalize; end ASF.Sessions;
Delete the principal object when the session is deleted.
Delete the principal object when the session is deleted.
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6eb0f13264eebe807976817b63d2291a8eda3003
examples/filesystem/src/main.adb
examples/filesystem/src/main.adb
with HAL; use HAL; with Virtual_File_System; use Virtual_File_System; with HAL.Filesystem; use HAL.Filesystem; with Semihosting; with Semihosting.Filesystem; use Semihosting.Filesystem; procedure Main is My_VFS : VFS; My_VFS2 : aliased VFS; My_VFS3 : aliased VFS; My_SHFS : aliased SHFS; Status : Status_Kind; FH : File_Handle_Ref; Data : Byte_Array (1 .. 10); begin Status := My_VFS.Mount (Path => "test1", Filesystem => My_VFS2'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS2.Mount (Path => "test2", Filesystem => My_VFS3'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS.Mount (Path => "host", Filesystem => My_SHFS'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("//test1/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1//no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1/test2/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Open ("/host/tmp/test.shfs", FH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Error: " & Status'Img); end if; Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Seek (10); if Status /= Status_Ok then Semihosting.Log_Line ("Seek Error: " & Status'Img); end if; Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Close; if Status /= Status_Ok then Semihosting.Log_Line ("Close Error: " & Status'Img); end if; end Main;
with HAL; use HAL; with Virtual_File_System; use Virtual_File_System; with HAL.Filesystem; use HAL.Filesystem; with Semihosting; with Semihosting.Filesystem; use Semihosting.Filesystem; procedure Main is procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname); procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname) is Status : Status_Kind; DH : Directory_Handle_Ref; begin Status := FS.Open_Directory (Path, DH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Directory '" & Path & "' Error: " & Status'Img); else declare Ent : Directory_Entry; Index : Positive := 1; begin Semihosting.Log_Line ("Listing '" & Path & "' content:"); loop Status := DH.Read_Entry (Index, Ent); if Status = Status_Ok then Semihosting.Log_Line (" - '" & DH.Entry_Name (Index) & "'"); Semihosting.Log_Line (" Kind: " & Ent.Entry_Type'Img); else exit; end if; Index := Index + 1; end loop; end; end if; end List_Dir; My_VFS : VFS; My_VFS2 : aliased VFS; My_VFS3 : aliased VFS; My_SHFS : aliased SHFS; Status : Status_Kind; FH : File_Handle_Ref; Data : Byte_Array (1 .. 10); begin Status := My_VFS.Mount (Path => "test1", Filesystem => My_VFS2'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS2.Mount (Path => "test2", Filesystem => My_VFS3'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS.Mount (Path => "host", Filesystem => My_SHFS'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("//test1/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1//no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1/test2/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Open ("/host/tmp/test.shfs", FH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Error: " & Status'Img); end if; Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Seek (10); if Status /= Status_Ok then Semihosting.Log_Line ("Seek Error: " & Status'Img); end if; Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Close; if Status /= Status_Ok then Semihosting.Log_Line ("Close Error: " & Status'Img); end if; List_Dir (My_VFS, "/"); List_Dir (My_VFS, "/test1"); List_Dir (My_VFS, "/test1/"); end Main;
Add directory listing example
example/filesystem: Add directory listing example
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
31536493af4999a38ad2bd9011a0e45cbc60e47a
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Add the SQL length to control the length of some SQL types
Add the SQL length to control the length of some SQL types
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
5f51dbd4eba2a8bb402514723aa82b3e898366ee
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.ads
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.ads
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Util.Properties; with AWS.SMTP; with AWS.SMTP.Authentication.Plain; private with AWS.Attachments; -- The <b>AWA.Mail.Clients.AWS_SMTP</b> package provides an implementation of the -- mail client interfaces on top of AWS SMTP client API. package AWA.Mail.Clients.AWS_SMTP is NAME : constant String := "smtp"; -- ------------------------------ -- Mail Message -- ------------------------------ -- The <b>Mail_Message</b> represents an abstract mail message that can be initialized -- before being sent. type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with private; type AWS_Mail_Message_Access is access all AWS_Mail_Message'Class; -- Set the <tt>From</tt> part of the message. overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String); -- Add a recipient for the message. overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String); -- Set the subject of the message. overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String); -- Set the body of the message. overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Alternative : in Unbounded_String; Content_Type : in String); -- Add an attachment with the given content. overriding procedure Add_Attachment (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Content_Id : in String; Content_Type : in String); -- Send the email message. overriding procedure Send (Message : in out AWS_Mail_Message); -- Deletes the mail message. overriding procedure Finalize (Message : in out AWS_Mail_Message); -- ------------------------------ -- Mail Manager -- ------------------------------ -- The <b>Mail_Manager</b> is the entry point to create a new mail message -- and be able to send it. type AWS_Mail_Manager is new Mail_Manager with private; type AWS_Mail_Manager_Access is access all AWS_Mail_Manager'Class; -- Create a SMTP based mail manager and configure it according to the properties. function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access; -- Create a new mail message. overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access; private type Recipients_Access is access all AWS.SMTP.Recipients; type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with record Manager : AWS_Mail_Manager_Access; From : AWS.SMTP.E_Mail_Data; Subject : Ada.Strings.Unbounded.Unbounded_String; -- Content : Ada.Strings.Unbounded.Unbounded_String; To : Recipients_Access := null; Attachments : AWS.Attachments.List; end record; type AWS_Mail_Manager is new Mail_Manager with record Self : AWS_Mail_Manager_Access; Server : AWS.SMTP.Receiver; Creds : aliased AWS.SMTP.Authentication.Plain.Credential; Port : Positive := 25; Enable : Boolean := True; Secure : Boolean := False; Auth : Boolean := False; end record; procedure Initialize (Client : in out AWS_Mail_Manager'Class; Props : in Util.Properties.Manager'Class); end AWA.Mail.Clients.AWS_SMTP;
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Util.Properties; with AWS.SMTP; with AWS.SMTP.Authentication.Plain; private with AWS.Attachments; -- The <b>AWA.Mail.Clients.AWS_SMTP</b> package provides an implementation of the -- mail client interfaces on top of AWS SMTP client API. package AWA.Mail.Clients.AWS_SMTP is NAME : constant String := "smtp"; -- ------------------------------ -- Mail Message -- ------------------------------ -- The <b>Mail_Message</b> represents an abstract mail message that can be initialized -- before being sent. type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with private; type AWS_Mail_Message_Access is access all AWS_Mail_Message'Class; -- Set the <tt>From</tt> part of the message. overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String); -- Add a recipient for the message. overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String); -- Set the subject of the message. overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String); -- Set the body of the message. overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Alternative : in Unbounded_String; Content_Type : in String); -- Add an attachment with the given content. overriding procedure Add_Attachment (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Content_Id : in String; Content_Type : in String); -- Send the email message. overriding procedure Send (Message : in out AWS_Mail_Message); -- Deletes the mail message. overriding procedure Finalize (Message : in out AWS_Mail_Message); -- ------------------------------ -- Mail Manager -- ------------------------------ -- The <b>Mail_Manager</b> is the entry point to create a new mail message -- and be able to send it. type AWS_Mail_Manager is new Mail_Manager with private; type AWS_Mail_Manager_Access is access all AWS_Mail_Manager'Class; -- Create a SMTP based mail manager and configure it according to the properties. function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access; -- Create a new mail message. overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access; private type Recipients_Access is access all AWS.SMTP.Recipients; type Recipients_Array is array (Recipient_Type) of Recipients_Access; type AWS_Mail_Message is new Ada.Finalization.Limited_Controlled and Mail_Message with record Manager : AWS_Mail_Manager_Access; From : AWS.SMTP.E_Mail_Data; Subject : Ada.Strings.Unbounded.Unbounded_String; To : Recipients_Array; Attachments : AWS.Attachments.List; end record; type AWS_Mail_Manager is new Mail_Manager with record Self : AWS_Mail_Manager_Access; Server : AWS.SMTP.Receiver; Creds : aliased AWS.SMTP.Authentication.Plain.Credential; Port : Positive := 25; Enable : Boolean := True; Secure : Boolean := False; Auth : Boolean := False; end record; procedure Initialize (Client : in out AWS_Mail_Manager'Class; Props : in Util.Properties.Manager'Class); end AWA.Mail.Clients.AWS_SMTP;
Declare Recipients_Array type to define the TO, CC, BCC recipients
Declare Recipients_Array type to define the TO, CC, BCC recipients
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a6d626af3565c7bd839d84ee8573a165ef35a5b7
src/util-properties.adb
src/util-properties.adb
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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.Properties.Factories; with Ada.Strings.Unbounded.Text_IO; package body Util.Properties is use Ada.Text_IO; use Ada.Strings.Unbounded.Text_IO; use Interface_P; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False); function Exists (Self : in Manager'Class; Name : in String) return Boolean is begin -- There is not yet an implementation, no property if Self.Impl = null then return False; end if; return Exists (Self.Impl.all, +Name); end Exists; function Exists (Self : in Manager'Class; Name : in Value) return Boolean is begin -- There is not yet an implementation, no property if Self.Impl = null then return False; end if; return Exists (Self.Impl.all, Name); end Exists; function Get (Self : in Manager'Class; Name : in String) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return Get (Self.Impl.all, +Name); end Get; function Get (Self : in Manager'Class; Name : in Value) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & To_String (Name) & "'"; end if; return Get (Self.Impl.all, Name); end Get; function Get (Self : in Manager'Class; Name : in String) return String is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return -Get (Self.Impl.all, +Name); end Get; function Get (Self : in Manager'Class; Name : in Value) return String is begin if Self.Impl = null then raise NO_PROPERTY; end if; return -Get (Self.Impl.all, Name); end Get; function Get (Self : in Manager'Class; Name : in String; Default : in String) return String is Prop_Name : constant Value := +Name; begin if Exists (Self, Prop_Name) then return Get (Self, Prop_Name); else return Default; end if; end Get; procedure Check_And_Create_Impl (Self : in out Manager) is begin if Self.Impl = null then Util.Properties.Factories.Initialize (Self); Self.Impl.Count := 1; elsif Self.Impl.Count > 1 then declare Old : constant Interface_P.Manager_Access := Self.Impl; begin Self.Impl := Create_Copy (Self.Impl.all); Self.Impl.Count := 1; Old.Count := Old.Count - 1; end; end if; end Check_And_Create_Impl; procedure Insert (Self : in out Manager'Class; Name : in String; Item : in String) is begin Check_And_Create_Impl (Self); Insert (Self.Impl.all, +Name, +Item); end Insert; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Item : in String) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, +Name, +Item); end Set; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, +Name, Item); end Set; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, Name, Item); end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in String) is begin if Self.Impl = null then raise NO_PROPERTY; end if; Remove (Self.Impl.all, +Name); end Remove; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in Value) is begin if Self.Impl = null then raise NO_PROPERTY; end if; Remove (Self.Impl.all, Name); end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)) is begin if Self.Impl /= null then Self.Impl.Iterate (Process); end if; end Iterate; -- ------------------------------ -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. -- ------------------------------ function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array is begin if Self.Impl = null then declare Empty : Name_Array (1 .. 0); begin return Empty; end; else return Get_Names (Self.Impl.all, Prefix); end if; end Get_Names; procedure Adjust (Object : in out Manager) is begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count + 1; end if; end Adjust; procedure Finalize (Object : in out Manager) is begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count - 1; if Object.Impl.Count = 0 then Delete (Object.Impl.all, Object.Impl); end if; end if; end Finalize; procedure Set_Property_Implementation (Self : in out Manager; Impl : in Interface_P.Manager_Access) is begin if Self.Impl = null then Self.Impl := Impl; Self.Impl.Count := 1; end if; end Set_Property_Implementation; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is pragma Unreferenced (Strip); Line : Unbounded_String; Pos : Natural; Len : Natural; begin while not End_Of_File (File) loop Line := Get_Line (File); Len := Length (Line); if Len /= 0 and then Element (Line, 1) /= '#' then Pos := Index (Line, "="); if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1); Value := Tail (Line, Len - Pos); return; elsif Pos > 0 and Prefix'Length = 0 then Name := Head (Line, Pos - 1); Value := Tail (Line, Len - Pos); return; end if; end if; end loop; Name := Null_Unbounded_String; Value := Null_Unbounded_String; end Load_Property; procedure Load_Properties (Self : in out Manager'Class; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is Name, Value : Unbounded_String; begin loop Load_Property (Name, Value, File, Prefix, Strip); exit when Name = Null_Unbounded_String; Set (Self, Name, Value); end loop; exception when End_Error => return; end Load_Properties; procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False) is F : File_Type; begin Open (F, In_File, Path); Load_Properties (Self, F, Prefix, Strip); Close (F); end Load_Properties; -- ------------------------------ -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- ------------------------------ procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False) is Names : constant Name_Array := From.Get_Names; begin for I in Names'Range loop declare Name : Unbounded_String renames Names (I); begin if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then if Strip and Prefix'Length > 0 then declare S : constant String := Slice (Name, Prefix'Length + 1, Length (Name)); begin Self.Set (+(S), From.Get (Name)); end; else Self.Set (Name, From.Get (Name)); end if; end if; end; end loop; end Copy; end Util.Properties;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Factories; with Ada.Strings.Unbounded.Text_IO; package body Util.Properties is use Ada.Text_IO; use Ada.Strings.Unbounded.Text_IO; use Interface_P; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False); function Exists (Self : in Manager'Class; Name : in String) return Boolean is begin -- There is not yet an implementation, no property if Self.Impl = null then return False; end if; return Exists (Self.Impl.all, +Name); end Exists; function Exists (Self : in Manager'Class; Name : in Value) return Boolean is begin -- There is not yet an implementation, no property if Self.Impl = null then return False; end if; return Exists (Self.Impl.all, Name); end Exists; function Get (Self : in Manager'Class; Name : in String) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return Get (Self.Impl.all, +Name); end Get; function Get (Self : in Manager'Class; Name : in Value) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & To_String (Name) & "'"; end if; return Get (Self.Impl.all, Name); end Get; function Get (Self : in Manager'Class; Name : in String) return String is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return -Get (Self.Impl.all, +Name); end Get; function Get (Self : in Manager'Class; Name : in Value) return String is begin if Self.Impl = null then raise NO_PROPERTY; end if; return -Get (Self.Impl.all, Name); end Get; function Get (Self : in Manager'Class; Name : in String; Default : in String) return String is Prop_Name : constant Value := +Name; begin if Exists (Self, Prop_Name) then return Get (Self, Prop_Name); else return Default; end if; end Get; procedure Check_And_Create_Impl (Self : in out Manager) is begin if Self.Impl = null then Util.Properties.Factories.Initialize (Self); elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then declare Old : Interface_P.Manager_Access := Self.Impl; Is_Zero : Boolean; begin Self.Impl := Create_Copy (Self.Impl.all); Util.Concurrent.Counters.Increment (Self.Impl.Count); Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero); if Is_Zero then Delete (Old.all, Old); end if; end; end if; end Check_And_Create_Impl; procedure Insert (Self : in out Manager'Class; Name : in String; Item : in String) is begin Check_And_Create_Impl (Self); Insert (Self.Impl.all, +Name, +Item); end Insert; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Item : in String) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, +Name, +Item); end Set; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, +Name, Item); end Set; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, Name, Item); end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in String) is begin if Self.Impl = null then raise NO_PROPERTY; end if; Check_And_Create_Impl (Self); Remove (Self.Impl.all, +Name); end Remove; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in Value) is begin if Self.Impl = null then raise NO_PROPERTY; end if; Check_And_Create_Impl (Self); Remove (Self.Impl.all, Name); end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)) is begin if Self.Impl /= null then Self.Impl.Iterate (Process); end if; end Iterate; -- ------------------------------ -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. -- ------------------------------ function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array is begin if Self.Impl = null then declare Empty : Name_Array (1 .. 0); begin return Empty; end; else return Get_Names (Self.Impl.all, Prefix); end if; end Get_Names; procedure Adjust (Object : in out Manager) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Count); end if; end Adjust; procedure Finalize (Object : in out Manager) is Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero); if Is_Zero then Delete (Object.Impl.all, Object.Impl); end if; end if; end Finalize; procedure Set_Property_Implementation (Self : in out Manager; Impl : in Interface_P.Manager_Access) is begin if Self.Impl = null then Self.Impl := Impl; -- Self.Impl.Count := 1; end if; end Set_Property_Implementation; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is pragma Unreferenced (Strip); Line : Unbounded_String; Pos : Natural; Len : Natural; begin while not End_Of_File (File) loop Line := Get_Line (File); Len := Length (Line); if Len /= 0 and then Element (Line, 1) /= '#' then Pos := Index (Line, "="); if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1); Value := Tail (Line, Len - Pos); return; elsif Pos > 0 and Prefix'Length = 0 then Name := Head (Line, Pos - 1); Value := Tail (Line, Len - Pos); return; end if; end if; end loop; Name := Null_Unbounded_String; Value := Null_Unbounded_String; end Load_Property; procedure Load_Properties (Self : in out Manager'Class; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is Name, Value : Unbounded_String; begin loop Load_Property (Name, Value, File, Prefix, Strip); exit when Name = Null_Unbounded_String; Set (Self, Name, Value); end loop; exception when End_Error => return; end Load_Properties; procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False) is F : File_Type; begin Open (F, In_File, Path); Load_Properties (Self, F, Prefix, Strip); Close (F); end Load_Properties; -- ------------------------------ -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- ------------------------------ procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False) is Names : constant Name_Array := From.Get_Names; begin for I in Names'Range loop declare Name : Unbounded_String renames Names (I); begin if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then if Strip and Prefix'Length > 0 then declare S : constant String := Slice (Name, Prefix'Length + 1, Length (Name)); begin Self.Set (+(S), From.Get (Name)); end; else Self.Set (Name, From.Get (Name)); end if; end if; end; end loop; end Copy; end Util.Properties;
Update the implementation to use a concurrent counters for properties manager
Update the implementation to use a concurrent counters for properties manager
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1ac07576038ec2a724bc7c4334b9d3dc1d26826e
src/wiki-render-html.adb
src/wiki-render-html.adb
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 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.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Render the node instance from the document. -- ------------------------------ overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) 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.Render_Header (Header => Node.Header, Level => Node.Level); when Wiki.Nodes.N_LINE_BREAK => Engine.Output.Start_Element ("br"); Engine.Output.End_Element ("br"); when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Add_Blockquote (0); Engine.Output.Start_Element ("hr"); Engine.Output.End_Element ("hr"); when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; when Wiki.Nodes.N_INDENT => -- Engine.Indent_Level := Node.Level; null; when Wiki.Nodes.N_TEXT => Engine.Add_Text (Text => Node.Text, Format => Node.Format); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Quote); when Wiki.Nodes.N_LINK => if Node.Image then Engine.Render_Image (Doc, Node.Title, Node.Link_Attr); else Engine.Render_Link (Doc, Node.Title, Node.Link_Attr); end if; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Add_Blockquote (Node.Level); when Wiki.Nodes.N_TAG_START => Engine.Render_Tag (Doc, Node); end case; end Render; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start); Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes); begin if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := True; Engine.Need_Paragraph := False; end if; Engine.Output.Start_Element (Name.all); while Wiki.Attributes.Has_Element (Iter) loop Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := False; Engine.Need_Paragraph := True; end if; Engine.Output.End_Element (Name.all); end Render_Tag; -- ------------------------------ -- Render a section header in the document. -- ------------------------------ procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive) is begin Engine.Close_Paragraph; Engine.Add_Blockquote (0); case Level is when 1 => Engine.Output.Write_Wide_Element ("h1", Header); when 2 => Engine.Output.Write_Wide_Element ("h2", Header); when 3 => Engine.Output.Write_Wide_Element ("h3", Header); when 4 => Engine.Output.Write_Wide_Element ("h4", Header); when 5 => Engine.Output.Write_Wide_Element ("h5", Header); when 6 => Engine.Output.Write_Wide_Element ("h6", Header); when others => Engine.Output.Write_Wide_Element ("h3", Header); end case; end Render_Header; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Output.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Output.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Output.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Output.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Output.Start_Element ("ol"); else Document.Output.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Output.End_Element ("p"); end if; if Document.Has_Item then Document.Output.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Output.End_Element ("ol"); else Document.Output.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Output.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Output.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Exists : Boolean; Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "hreflang" or Name = "title" or Name = "rel" or Name = "target" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); Engine.Links.Make_Page_Link (Link, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "alt" or Name = "longdesc" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("img"); Engine.Links.Make_Image_Link (Link, URI, Width, Height); Engine.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Engine.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Engine.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.End_Element ("img"); end Render_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Open_Paragraph; Document.Output.Start_Element ("q"); if Length (Language) > 0 then Document.Output.Write_Wide_Attribute ("lang", Language); end if; if Length (Link) > 0 then Document.Output.Write_Wide_Attribute ("cite", Link); end if; Document.Output.Write_Wide_Text (Quote); Document.Output.End_Element ("q"); end Add_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (Documents.BOLD => HTML_BOLD'Access, Documents.ITALIC => HTML_ITALIC'Access, Documents.CODE => HTML_CODE'Access, Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access, Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access, Documents.STRIKEOUT => HTML_STRIKEOUT'Access, Documents.PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Documents.Format_Map) is begin Engine.Open_Paragraph; for I in Format'Range loop if Format (I) then Engine.Output.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Engine.Output.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Engine.Output.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Output.Write (Text); else Document.Output.Start_Element ("pre"); -- Document.Output.Write_Wide_Text (Text); Document.Output.End_Element ("pre"); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 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.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Render the node instance from the document. -- ------------------------------ overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) 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.Render_Header (Header => Node.Header, Level => Node.Level); when Wiki.Nodes.N_LINE_BREAK => Engine.Output.Start_Element ("br"); Engine.Output.End_Element ("br"); when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Add_Blockquote (0); Engine.Output.Start_Element ("hr"); Engine.Output.End_Element ("hr"); when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; when Wiki.Nodes.N_INDENT => -- Engine.Indent_Level := Node.Level; null; when Wiki.Nodes.N_TEXT => Engine.Add_Text (Text => Node.Text, Format => Node.Format); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); when Wiki.Nodes.N_LINK => Engine.Render_Link (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_BLOCKQUOTE => Engine.Add_Blockquote (Node.Level); when Wiki.Nodes.N_TAG_START => Engine.Render_Tag (Doc, Node); end case; end Render; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start); Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes); begin if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := True; Engine.Need_Paragraph := False; end if; Engine.Output.Start_Element (Name.all); while Wiki.Attributes.Has_Element (Iter) loop Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := False; Engine.Need_Paragraph := True; end if; Engine.Output.End_Element (Name.all); end Render_Tag; -- ------------------------------ -- Render a section header in the document. -- ------------------------------ procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive) is begin Engine.Close_Paragraph; Engine.Add_Blockquote (0); case Level is when 1 => Engine.Output.Write_Wide_Element ("h1", Header); when 2 => Engine.Output.Write_Wide_Element ("h2", Header); when 3 => Engine.Output.Write_Wide_Element ("h3", Header); when 4 => Engine.Output.Write_Wide_Element ("h4", Header); when 5 => Engine.Output.Write_Wide_Element ("h5", Header); when 6 => Engine.Output.Write_Wide_Element ("h6", Header); when others => Engine.Output.Write_Wide_Element ("h3", Header); end case; end Render_Header; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Output.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Output.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Output.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Output.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Output.Start_Element ("ol"); else Document.Output.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Output.End_Element ("p"); end if; if Document.Has_Item then Document.Output.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Output.End_Element ("ol"); else Document.Output.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Output.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Output.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Exists : Boolean; Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "hreflang" or Name = "title" or Name = "rel" or Name = "target" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); Engine.Links.Make_Page_Link (Link, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "alt" or Name = "longdesc" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("img"); Engine.Links.Make_Image_Link (Link, URI, Width, Height); Engine.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Engine.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Engine.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.End_Element ("img"); end Render_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Open_Paragraph; Document.Output.Start_Element ("q"); if Length (Language) > 0 then Document.Output.Write_Wide_Attribute ("lang", Language); end if; if Length (Link) > 0 then Document.Output.Write_Wide_Attribute ("cite", Link); end if; -- Document.Output.Write_Wide_Text (Quote); Document.Output.End_Element ("q"); end Add_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (Documents.BOLD => HTML_BOLD'Access, Documents.ITALIC => HTML_ITALIC'Access, Documents.CODE => HTML_CODE'Access, Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access, Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access, Documents.STRIKEOUT => HTML_STRIKEOUT'Access, Documents.PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Documents.Format_Map) is begin Engine.Open_Paragraph; for I in Format'Range loop if Format (I) then Engine.Output.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Engine.Output.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Engine.Output.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Output.Write (To_Wide_Wide_String (Text)); else Document.Output.Start_Element ("pre"); -- Document.Output.Write_Wide_Text (Text); Document.Output.End_Element ("pre"); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
Update the rendering of N_IMAGE and N_LINK
Update the rendering of N_IMAGE and N_LINK
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a17fd6fabc4d5028f17882c53549216821b09ad5
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Writers; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Html_Renderer is new Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Html_Renderer; Writer : in Wiki.Writers.Html_Writer_Type_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Html_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Html_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Html_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Html_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); overriding procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Wiki.Documents.Document_Reader with record Writer : Wiki.Writers.Html_Writer_Type_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Has_Item : Boolean := False; Quote_Level : Natural := 0; end record; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Writers; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Html_Renderer is new Wiki.Documents.Document_Reader with private; -- Set the output writer. procedure Set_Writer (Document : in out Html_Renderer; Writer : in Wiki.Writers.Html_Writer_Type_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- Add a section header in the document. overriding procedure Add_Header (Document : in out Html_Renderer; Header : in Unbounded_Wide_Wide_String; Level : in Positive); -- Add a line break (<br>). overriding procedure Add_Line_Break (Document : in out Html_Renderer); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. overriding procedure Add_Paragraph (Document : in out Html_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. overriding procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. overriding procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add an horizontal rule (<hr>). overriding procedure Add_Horizontal_Rule (Document : in out Html_Renderer); -- Add a link. overriding procedure Add_Link (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. overriding procedure Add_Image (Document : in out Html_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. overriding procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. overriding procedure Add_Text (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); overriding procedure Start_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); overriding procedure End_Element (Document : in out Html_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Wiki.Documents.Document_Reader with record Writer : Wiki.Writers.Html_Writer_Type_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Has_Item : Boolean := False; Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; end Wiki.Render.Html;
Add Html_Level to keep track whether we are in HTML wiki text or not
Add Html_Level to keep track whether we are in HTML wiki text or not
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9fc7693bdd6668f84995d412f51e9063c0612a57
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020, 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.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- === Wiki Renderer === -- The `Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; procedure Write_Optional_Space (Engine : in out Wiki_Renderer); -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Need_Newline : Boolean := False; Need_Space : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Natural := 0; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Html_Table : Boolean := False; In_Table : Boolean := False; Col_Index : Natural := 0; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; procedure Write_Link (Engine : in out Wiki_Renderer; Link : in Strings.WString); -- Render the table of content. procedure Render_TOC (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Level : in Natural); -- Render a table component such as N_TABLE. procedure Render_Table (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Render a table row component such as N_ROW. procedure Render_Row (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Render a table row component such as N_COLUMN. procedure Render_Column (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020, 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.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- === Wiki Renderer === -- The `Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type; Level : in Natural; List : in Nodes.Node_List_Access); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); procedure Render_List_Start (Engine : in out Wiki_Renderer; Numbered : in Boolean; Level : in Natural); procedure Render_List_End (Engine : in out Wiki_Renderer; Tag : in String); procedure Render_List_Item_Start (Engine : in out Wiki_Renderer); procedure Render_List_Item_End (Engine : in out Wiki_Renderer); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; procedure Write_Optional_Space (Engine : in out Wiki_Renderer); -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Index_Type is new Integer range 0 .. 32; type List_Level_Array is array (List_Index_Type range 1 .. 32) of Natural; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; List_Index : List_Index_Type := 0; List_Levels : List_Level_Array; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Need_Newline : Boolean := False; Need_Space : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Natural := 0; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Html_Table : Boolean := False; In_Table : Boolean := False; In_Header : Boolean := False; Col_Index : Natural := 0; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; Indent_Level : Natural := 0; end record; procedure Write_Link (Engine : in out Wiki_Renderer; Link : in Strings.WString); -- Render the table of content. procedure Render_TOC (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Level : in Natural); -- Render a table component such as N_TABLE. procedure Render_Table (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Render a table row component such as N_ROW. procedure Render_Row (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Render a table row component such as N_COLUMN. procedure Render_Column (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); end Wiki.Render.Wiki;
Rework the list rendering to take into account the new document nodes
Rework the list rendering to take into account the new document nodes
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
98bbba8c7604f6038327edb56d7338ee68c67b36
Ada/Benchmark/src/primes.adb
Ada/Benchmark/src/primes.adb
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; package body Primes is function Is_Prime (N : Natural) return Boolean is Limit : constant Natural := Natural (Sqrt (Float (N))); begin if N < 2 then return False; end if; for I in 2 .. Limit loop if N mod I = 0 then return False; end if; end loop; return True; end Is_Prime; function Is_Prime (N : Big_Natural) return Boolean is Limit : constant Big_Natural := N / 2; I : Big_Natural := To_Big_Integer (2); begin if N < 2 then return False; end if; while I < Limit loop if N mod I = 0 then return False; end if; I := I + 1; end loop; return True; end Is_Prime; function Get_Primes (Limit : Natural) return Prime_Vectors.Vector is Result : Prime_Vectors.Vector; begin for I in 2 .. Limit loop if Is_Prime (I) then Result.Append (I); end if; end loop; return Result; end Get_Primes; function Get_Primes (Limit : Big_Natural) return Big_Prime_Vectors.Vector is I : Big_Natural := To_Big_Integer (2); Result : Big_Prime_Vectors.Vector; begin while I < Limit loop null; I := I + 1; if Is_Prime (I) then Result.Append (I); end if; end loop; return Result; end Get_Primes; end Primes;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; package body Primes is function Is_Prime (N : Natural) return Boolean is Limit : constant Natural := Natural (Sqrt (Float (N))); begin if N < 2 then return False; end if; for I in 2 .. Limit loop if N mod I = 0 then return False; end if; end loop; return True; end Is_Prime; function Is_Prime (N : Big_Natural) return Boolean is Limit : constant Big_Natural := N / To_Big_Integer (2); I : Big_Natural := To_Big_Integer (2); begin if N < To_Big_Integer (2) then return False; end if; while I < Limit loop if N mod I = To_Big_Integer (0) then return False; end if; I := I + To_Big_Integer (1); end loop; return True; end Is_Prime; function Get_Primes (Limit : Natural) return Prime_Vectors.Vector is Result : Prime_Vectors.Vector; begin for I in 2 .. Limit loop if Is_Prime (I) then Result.Append (I); end if; end loop; return Result; end Get_Primes; function Get_Primes (Limit : Big_Natural) return Big_Prime_Vectors.Vector is I : Big_Natural := To_Big_Integer (2); Result : Big_Prime_Vectors.Vector; begin while I < Limit loop null; I := I + To_Big_Integer (1); if Is_Prime (I) then Result.Append (I); end if; end loop; return Result; end Get_Primes; end Primes;
fix Big_Integer conversions
fix Big_Integer conversions
Ada
mit
kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground,kkirstein/proglang-playground
884df9b5f3f4a07f0bc393d3c3297e6095a5e2d4
src/ado-drivers-dialects.adb
src/ado-drivers-dialects.adb
----------------------------------------------------------------------- -- ADO Dialects -- Driver support for basic SQL Generation -- Copyright (C) 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. ----------------------------------------------------------------------- package body ADO.Drivers.Dialects is -- ------------------------------ -- Append the item in the buffer escaping some characters if necessary. -- The default implementation only escapes the single quote ' by doubling them. -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in String) is pragma Unreferenced (D); C : Character; begin Append (Buffer, '''); for I in Item'Range loop C := Item (I); if C = ''' then Append (Buffer, '''); end if; Append (Buffer, C); end loop; Append (Buffer, '''); end Escape_Sql; -- ------------------------------ -- Append the item in the buffer escaping some characters if necessary -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in ADO.Blob_Ref) is pragma Unreferenced (D); C : Ada.Streams.Stream_Element; Blob : constant ADO.Blob_Access := Item.Value; begin Append (Buffer, '''); for I in Blob.Data'Range loop C := Blob.Data (I); case C is when Character'Pos (ASCII.NUL) => Append (Buffer, '\'); Append (Buffer, '0'); when Character'Pos (ASCII.CR) => Append (Buffer, '\'); Append (Buffer, 'r'); when Character'Pos (ASCII.LF) => Append (Buffer, '\'); Append (Buffer, 'n'); when Character'Pos ('\') | Character'Pos (''') | Character'Pos ('"') => Append (Buffer, '\'); Append (Buffer, Character'Val (C)); when others => Append (Buffer, Character'Val (C)); end case; end loop; Append (Buffer, '''); end Escape_Sql; -- ------------------------------ -- Append the boolean item in the buffer. -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in Boolean) is pragma Unreferenced (D); begin Append (Buffer, (if Item then '1' else '0')); end Escape_Sql; end ADO.Drivers.Dialects;
----------------------------------------------------------------------- -- ADO Dialects -- Driver support for basic SQL Generation -- Copyright (C) 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. ----------------------------------------------------------------------- package body ADO.Drivers.Dialects is -- ------------------------------ -- Append the item in the buffer escaping some characters if necessary. -- The default implementation only escapes the single quote ' by doubling them. -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in String) is pragma Unreferenced (D); C : Character; begin Append (Buffer, '''); for I in Item'Range loop C := Item (I); if C = ''' then Append (Buffer, '''); end if; Append (Buffer, C); end loop; Append (Buffer, '''); end Escape_Sql; -- ------------------------------ -- Append the boolean item in the buffer. -- ------------------------------ procedure Escape_Sql (D : in Dialect; Buffer : in out Unbounded_String; Item : in Boolean) is pragma Unreferenced (D); begin Append (Buffer, (if Item then '1' else '0')); end Escape_Sql; end ADO.Drivers.Dialects;
Make Escape_Sql procedure abstract
Make Escape_Sql procedure abstract
Ada
apache-2.0
stcarrez/ada-ado
0dcd28ed9b52b80f3c2dcc985551b671816e01ba
regtests/util-texts-builders_tests.adb
regtests/util-texts-builders_tests.adb
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Text_IO; with Util.Test_Caller; with Util.Texts.Builders; with Util.Measures; package body Util.Texts.Builders_Tests is package String_Builder is new Util.Texts.Builders (Element_Type => Character, Input => String, Chunk_Size => 100); package Caller is new Util.Test_Caller (Test, "Texts.Builders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length", Test_Length'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append", Test_Append'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear", Test_Clear'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate", Test_Iterate'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf", Test_Perf'Access); end Add_Tests; -- ------------------------------ -- Test the length operation. -- ------------------------------ procedure Test_Length (T : in out Test) is B : String_Builder.Builder (10); begin Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity"); end Test_Length; -- ------------------------------ -- Test the append operation. -- ------------------------------ procedure Test_Append (T : in out Test) is S : constant String := "0123456789"; B : String_Builder.Builder (3); begin String_Builder.Append (B, "a string"); Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); -- Append new string and check content. String_Builder.Append (B, " b string"); Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); for I in S'Range loop String_Builder.Append (B, S (I)); end loop; Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append"); end Test_Append; -- ------------------------------ -- Test the clear operation. -- ------------------------------ procedure Test_Clear (T : in out Test) is B : String_Builder.Builder (7); begin for I in 1 .. 10 loop String_Builder.Append (B, "a string"); end loop; Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear"); Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear"); end Test_Clear; -- ------------------------------ -- Test the iterate operation. -- ------------------------------ procedure Test_Iterate (T : in out Test) is procedure Process (S : in String); B : String_Builder.Builder (13); R : Ada.Strings.Unbounded.Unbounded_String; procedure Process (S : in String) is begin Ada.Strings.Unbounded.Append (R, S); end Process; begin for I in 1 .. 100 loop String_Builder.Append (B, "The Iterate procedure avoids the string copy " & "on the secondary stack"); end loop; String_Builder.Iterate (B, Process'Access); Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R), "Invalid length in iterate string"); Util.Tests.Assert_Equals (T, String_Builder.To_Array (B), Ada.Strings.Unbounded.To_String (R), "Invalid Iterate"); end Test_Iterate; -- ------------------------------ -- Test the append and iterate performance. -- ------------------------------ procedure Test_Perf (T : in out Test) is Perf : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string-append.csv")); Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time"); for Block_Size in 1 .. 300 loop declare B : String_Builder.Builder (10); N : constant String := Natural'Image (Block_Size * 10) & ","; begin String_Builder.Set_Block_Size (B, Block_Size * 10); declare S : Util.Measures.Stamp; begin for I in 1 .. 1000 loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); end; declare S : Util.Measures.Stamp; R : constant String := String_Builder.To_Array (B); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (R'Length > 0, "Invalid string length"); end; declare Count : Natural := 0; procedure Process (Item : in String); procedure Process (Item : in String) is pragma Unreferenced (Item); begin Count := Count + 1; end Process; S : Util.Measures.Stamp; begin String_Builder.Iterate (B, Process'Access); Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (Count > 0, "The string builder was empty"); end; end; Ada.Text_IO.New_Line (Perf); end loop; Ada.Text_IO.Close (Perf); Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string.csv")); Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512)," & "Append (1024),Unbounded,Iterate Time"); for I in 1 .. 4000 loop declare N : constant String := Natural'Image (I) & ","; B : String_Builder.Builder (10); B2 : String_Builder.Builder (10); B3 : String_Builder.Builder (10); U : Ada.Strings.Unbounded.Unbounded_String; S : Util.Measures.Stamp; begin for J in 1 .. I loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); String_Builder.Set_Block_Size (B2, 512); for J in 1 .. I loop String_Builder.Append (B2, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); String_Builder.Set_Block_Size (B3, 1024); for J in 1 .. I loop String_Builder.Append (B3, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); for J in 1 .. I loop Ada.Strings.Unbounded.Append (U, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); declare R : constant String := String_Builder.To_Array (B); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; declare R : constant String := Ada.Strings.Unbounded.To_String (U); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; end; Ada.Text_IO.New_Line (Perf); end loop; end Test_Perf; end Util.Texts.Builders_Tests;
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- 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.Strings.Unbounded; with Ada.Text_IO; with Util.Test_Caller; with Util.Texts.Builders; with Util.Measures; package body Util.Texts.Builders_Tests is package String_Builder is new Util.Texts.Builders (Element_Type => Character, Input => String, Chunk_Size => 100); package Caller is new Util.Test_Caller (Test, "Texts.Builders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length", Test_Length'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append", Test_Append'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear", Test_Clear'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate", Test_Iterate'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail", Test_Tail'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf", Test_Perf'Access); end Add_Tests; -- ------------------------------ -- Test the length operation. -- ------------------------------ procedure Test_Length (T : in out Test) is B : String_Builder.Builder (10); begin Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity"); end Test_Length; -- ------------------------------ -- Test the append operation. -- ------------------------------ procedure Test_Append (T : in out Test) is S : constant String := "0123456789"; B : String_Builder.Builder (3); begin String_Builder.Append (B, "a string"); Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); -- Append new string and check content. String_Builder.Append (B, " b string"); Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); for I in S'Range loop String_Builder.Append (B, S (I)); end loop; Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append"); end Test_Append; -- ------------------------------ -- Test the clear operation. -- ------------------------------ procedure Test_Clear (T : in out Test) is B : String_Builder.Builder (7); begin for I in 1 .. 10 loop String_Builder.Append (B, "a string"); end loop; Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear"); Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear"); end Test_Clear; -- ------------------------------ -- Test the tail operation. -- ------------------------------ procedure Test_Tail (T : in out Test) is procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural); procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural) is P : constant String := "0123456789"; B : String_Builder.Builder (Min); begin for I in 1 .. Max loop String_Builder.Append (B, P (1 + (I mod 10))); end loop; declare S : constant String := String_Builder.Tail (B, L); S2 : constant String := String_Builder.To_Array (B); begin Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length"); if L >= Max then Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result"); else Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1.. S2'Last), S, "Invalid Tail result {" & Positive'Image (Min) & "," & Positive'Image (Max) & "," & Positive'Image (L) & "]"); end if; end; end Check_Tail; begin for I in 1 .. 100 loop for J in 1 .. 8 loop for K in 1 .. I + 3 loop Check_Tail (J, I, K); end loop; end loop; end loop; end Test_Tail; -- ------------------------------ -- Test the iterate operation. -- ------------------------------ procedure Test_Iterate (T : in out Test) is procedure Process (S : in String); B : String_Builder.Builder (13); R : Ada.Strings.Unbounded.Unbounded_String; procedure Process (S : in String) is begin Ada.Strings.Unbounded.Append (R, S); end Process; begin for I in 1 .. 100 loop String_Builder.Append (B, "The Iterate procedure avoids the string copy " & "on the secondary stack"); end loop; String_Builder.Iterate (B, Process'Access); Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R), "Invalid length in iterate string"); Util.Tests.Assert_Equals (T, String_Builder.To_Array (B), Ada.Strings.Unbounded.To_String (R), "Invalid Iterate"); end Test_Iterate; -- ------------------------------ -- Test the append and iterate performance. -- ------------------------------ procedure Test_Perf (T : in out Test) is Perf : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string-append.csv")); Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time"); for Block_Size in 1 .. 300 loop declare B : String_Builder.Builder (10); N : constant String := Natural'Image (Block_Size * 10) & ","; begin String_Builder.Set_Block_Size (B, Block_Size * 10); declare S : Util.Measures.Stamp; begin for I in 1 .. 1000 loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); end; declare S : Util.Measures.Stamp; R : constant String := String_Builder.To_Array (B); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (R'Length > 0, "Invalid string length"); end; declare Count : Natural := 0; procedure Process (Item : in String); procedure Process (Item : in String) is pragma Unreferenced (Item); begin Count := Count + 1; end Process; S : Util.Measures.Stamp; begin String_Builder.Iterate (B, Process'Access); Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (Count > 0, "The string builder was empty"); end; end; Ada.Text_IO.New_Line (Perf); end loop; Ada.Text_IO.Close (Perf); Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string.csv")); Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512)," & "Append (1024),Unbounded,Iterate Time"); for I in 1 .. 4000 loop declare N : constant String := Natural'Image (I) & ","; B : String_Builder.Builder (10); B2 : String_Builder.Builder (10); B3 : String_Builder.Builder (10); U : Ada.Strings.Unbounded.Unbounded_String; S : Util.Measures.Stamp; begin for J in 1 .. I loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); String_Builder.Set_Block_Size (B2, 512); for J in 1 .. I loop String_Builder.Append (B2, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); String_Builder.Set_Block_Size (B3, 1024); for J in 1 .. I loop String_Builder.Append (B3, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); for J in 1 .. I loop Ada.Strings.Unbounded.Append (U, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); declare R : constant String := String_Builder.To_Array (B); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; declare R : constant String := Ada.Strings.Unbounded.To_String (U); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; end; Ada.Text_IO.New_Line (Perf); end loop; end Test_Perf; end Util.Texts.Builders_Tests;
Implement Test_Tail procedure
Implement Test_Tail procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1ba728b5dc2e88bba81cb0d41a3598fcb15a266c
regtests/util-encoders-ecc-tests.adb
regtests/util-encoders-ecc-tests.adb
----------------------------------------------------------------------- -- util-encodes-ecc-tests - ECC function tests -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Util.Test_Caller; with Util.Measures; with Util.Strings.Transforms; with Ada.Text_IO; package body Util.Encoders.ECC.Tests is use Util.Tests; use Interfaces; package Caller is new Util.Test_Caller (Test, "Encoders.ECC"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Encoders.ECC.Make+Check (256)", Test_ECC_Block_256'Access); Caller.Add_Test (Suite, "Test Util.Encoders.ECC.Make+Check (512)", Test_ECC_Block_512'Access); end Add_Tests; procedure Assert_Equals (T : in out Test; Expect : in ECC_Code; Code : in ECC_Code; Message : in String) is begin Util.Tests.Assert_Equals (T, Natural (Expect (0)), Natural (Code (0)), "ECC(0): " & Message); Util.Tests.Assert_Equals (T, Natural (Expect (1)), Natural (Code (1)), "ECC(1): " & Message); Util.Tests.Assert_Equals (T, Natural (Expect (2)), Natural (Code (2)), "ECC(2): " & Message); end Assert_Equals; -- ------------------------------ -- Test ECC correction on 256 bytes block. -- ------------------------------ procedure Test_ECC_Block (T : in out Test; Data : in Ada.Streams.Stream_Element_Array; Expect : in ECC_Code; Title : in String) is Data2 : Ada.Streams.Stream_Element_Array := Data; Code1 : ECC_Code; Code2 : ECC_Code; Result : ECC_Result; begin Make (Data, Code1); Assert_Equals (T, Expect, Code1, Title); for I in Data'Range loop for J in 0 .. 7 loop Data2 (I) := Data2 (I) xor Stream_Element (Shift_Left (Unsigned_8 (1), J)); Make (Data2, Code2); -- Assert_Equals (T, (16#59#, 16#a6#, 16#5a#), Code2, "Zero block (1 bit error)"); Result := Correct (Data2, Expect); T.Assert (Result = CORRECTABLE_ERROR, Title & ": not corrected" & Natural'Image (Natural (I)) & " bit" & Natural'Image (J)); Make (Data2, Code2); Assert_Equals (T, Expect, Code2, Title & ": bad ECC" & Natural'Image (Natural (I)) & " bit" & Natural'Image (J)); T.Assert (Data = Data2, Title & ": invalid data block"); end loop; end loop; end Test_ECC_Block; -- ------------------------------ -- Test ECC correction on 256 bytes block. -- ------------------------------ procedure Test_ECC_Block_256 (T : in out Test) is Data : Ada.Streams.Stream_Element_Array (0 .. 255) := (others => 0); begin Test_ECC_Block (T, Data, (16#ff#, 16#ff#, 16#ff#), "Zero block"); Data (45) := 16#20#; Test_ECC_Block (T, Data, (16#59#, 16#a6#, 16#67#), "Zero block, @45=20"); Data (45) := 16#10#; Test_ECC_Block (T, Data, (16#59#, 16#a6#, 16#6b#), "Zero block, @45=10"); Data (45) := 16#41#; Test_ECC_Block (T, Data, (16#ff#, 16#ff#, 16#0f#), "Zero block, @45=41"); end Test_ECC_Block_256; -- ------------------------------ -- Test ECC correction on 512 bytes block. -- ------------------------------ procedure Test_ECC_Block_512 (T : in out Test) is Data : Ada.Streams.Stream_Element_Array (0 .. 511) := (others => 0); begin Test_ECC_Block (T, Data, (16#ff#, 16#ff#, 16#ff#), "Zero block 512"); Data (45) := 16#20#; Test_ECC_Block (T, Data, (16#59#, 16#a6#, 16#66#), "Zero block 512, @45=20"); Data (45) := 16#10#; Test_ECC_Block (T, Data, (16#59#, 16#a6#, 16#6a#), "Zero block 512, @45=10"); Data (45) := 16#41#; Test_ECC_Block (T, Data, (16#ff#, 16#ff#, 16#0f#), "Zero block 512, @45=41"); end Test_ECC_Block_512; end Util.Encoders.ECC.Tests;
----------------------------------------------------------------------- -- util-encodes-ecc-tests - ECC function tests -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Util.Test_Caller; package body Util.Encoders.ECC.Tests is use Interfaces; package Caller is new Util.Test_Caller (Test, "Encoders.ECC"); procedure Assert_Equals (T : in out Test; Expect : in ECC_Code; Code : in ECC_Code; Message : in String); procedure Test_ECC_Block (T : in out Test; Data : in Ada.Streams.Stream_Element_Array; Expect : in ECC_Code; Title : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Encoders.ECC.Make+Check (256)", Test_ECC_Block_256'Access); Caller.Add_Test (Suite, "Test Util.Encoders.ECC.Make+Check (512)", Test_ECC_Block_512'Access); end Add_Tests; procedure Assert_Equals (T : in out Test; Expect : in ECC_Code; Code : in ECC_Code; Message : in String) is begin Util.Tests.Assert_Equals (T, Natural (Expect (0)), Natural (Code (0)), "ECC(0): " & Message); Util.Tests.Assert_Equals (T, Natural (Expect (1)), Natural (Code (1)), "ECC(1): " & Message); Util.Tests.Assert_Equals (T, Natural (Expect (2)), Natural (Code (2)), "ECC(2): " & Message); end Assert_Equals; -- ------------------------------ -- Test ECC correction on 256 bytes block. -- ------------------------------ procedure Test_ECC_Block (T : in out Test; Data : in Ada.Streams.Stream_Element_Array; Expect : in ECC_Code; Title : in String) is Data2 : Ada.Streams.Stream_Element_Array := Data; Code1 : ECC_Code; Code2 : ECC_Code; Code3 : ECC_Code; Result : ECC_Result; begin Make (Data, Code1); Assert_Equals (T, Expect, Code1, Title); for I in Data'Range loop for J in 0 .. 7 loop Data2 (I) := Data2 (I) xor Stream_Element (Shift_Left (Unsigned_8 (1), J)); Make (Data2, Code2); Result := Correct (Data2, Expect); T.Assert (Result = CORRECTABLE_ERROR, Title & ": not corrected" & Natural'Image (Natural (I)) & " bit" & Natural'Image (J)); Make (Data2, Code3); Assert_Equals (T, Expect, Code3, Title & ": bad ECC" & Natural'Image (Natural (I)) & " bit" & Natural'Image (J)); T.Assert (Data = Data2, Title & ": invalid data block"); end loop; end loop; end Test_ECC_Block; -- ------------------------------ -- Test ECC correction on 256 bytes block. -- ------------------------------ procedure Test_ECC_Block_256 (T : in out Test) is Data : Ada.Streams.Stream_Element_Array (0 .. 255) := (others => 0); begin Test_ECC_Block (T, Data, (16#ff#, 16#ff#, 16#ff#), "Zero block"); Data (45) := 16#20#; Test_ECC_Block (T, Data, (16#59#, 16#a6#, 16#67#), "Zero block, @45=20"); Data (45) := 16#10#; Test_ECC_Block (T, Data, (16#59#, 16#a6#, 16#6b#), "Zero block, @45=10"); Data (45) := 16#41#; Test_ECC_Block (T, Data, (16#ff#, 16#ff#, 16#0f#), "Zero block, @45=41"); end Test_ECC_Block_256; -- ------------------------------ -- Test ECC correction on 512 bytes block. -- ------------------------------ procedure Test_ECC_Block_512 (T : in out Test) is Data : Ada.Streams.Stream_Element_Array (0 .. 511) := (others => 0); begin Test_ECC_Block (T, Data, (16#ff#, 16#ff#, 16#ff#), "Zero block 512"); Data (45) := 16#20#; Test_ECC_Block (T, Data, (16#59#, 16#a6#, 16#66#), "Zero block 512, @45=20"); Data (45) := 16#10#; Test_ECC_Block (T, Data, (16#59#, 16#a6#, 16#6a#), "Zero block 512, @45=10"); Data (45) := 16#41#; Test_ECC_Block (T, Data, (16#ff#, 16#ff#, 16#0f#), "Zero block 512, @45=41"); end Test_ECC_Block_512; end Util.Encoders.ECC.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6867eee52ad4b87a4d66af1c729174d95dcd7fc1
src/util-events-channels.adb
src/util-events-channels.adb
----------------------------------------------------------------------- -- events-channel -- Event Channels -- Copyright (C) 2001, 2002, 2003, 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.Strings; package body Util.Events.Channels is use Containers; use Ada.Strings.Unbounded; use Util.Strings; type Factory_Line is record Name : Name_Access; Creator : Channel_Creator; end record; type Factory_Table is array (Natural range <>) of Factory_Line; DIRECT_NAME : aliased constant String := "direct"; Factory : constant Factory_Table (1 .. 1) := (1 => (Name => DIRECT_NAME'Access, Creator => Create_Direct_Channel'Access)); -- ----------------------- -- Get the name of this event channel. -- ----------------------- function Get_Name (C : Channel) return String is begin return To_String (C.Name); end Get_Name; -- ----------------------- -- Post an event and dispatch it immediately. -- ----------------------- procedure Post (To : in out Channel; Item : in Event'Class) is Iter : Cursor := First (To.Clients); begin -- Dispatch_One makes the connection between the common implementation -- and the generics while Has_Element (Iter) loop declare Client : constant Subscriber_Access := Element (Iter); begin Client.Receive_Event (Item); end; Iter := Next (Iter); end loop; end Post; -- ----------------------- -- Subscribe to events sent on the event channel. -- ----------------------- procedure Subscribe (To : in out Channel; Client : in Subscriber_Access) is begin pragma Assert (Client /= null, "Client subscriber must not be null"); Append (To.Clients, Client); end Subscribe; -- ----------------------- -- Unsubscribe to events sent on the event channel. -- ----------------------- procedure Unsubscribe (To : in out Channel; Client : in Subscriber_Access) is Iter : Cursor := First (To.Clients); begin while Has_Element (Iter) loop if Element (Iter) = Client then Delete (To.Clients, Iter); return; end if; Iter := Next (Iter); end loop; end Unsubscribe; -- ----------------------- -- Create an event channel with the given name. The type of channel -- is controlled by <b>Kind</b>. -- ----------------------- function Create (Name : String; Kind : String) return Channel_Access is begin for I in Factory'Range loop if Factory (I).Name.all = Kind then return Factory (I).Creator (Name); end if; end loop; return Create_Direct_Channel (Name); end Create; -- ----------------------- -- Create an event channel that post the event immediately. -- ----------------------- function Create_Direct_Channel (Name : String) return Channel_Access is Result : constant Channel_Access := new Channel; begin Result.Name := To_Unbounded_String (Name); return Result; end Create_Direct_Channel; end Util.Events.Channels;
----------------------------------------------------------------------- -- util-events-channel -- Event Channels -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body Util.Events.Channels is use Containers; use Ada.Strings.Unbounded; use Util.Strings; type Factory_Line is record Name : Name_Access; Creator : Channel_Creator; end record; type Factory_Table is array (Natural range <>) of Factory_Line; DIRECT_NAME : aliased constant String := "direct"; Factory : constant Factory_Table (1 .. 1) := (1 => (Name => DIRECT_NAME'Access, Creator => Create_Direct_Channel'Access)); -- ----------------------- -- Get the name of this event channel. -- ----------------------- function Get_Name (C : Channel) return String is begin return To_String (C.Name); end Get_Name; -- ----------------------- -- Post an event and dispatch it immediately. -- ----------------------- procedure Post (To : in out Channel; Item : in Event'Class) is Iter : Cursor := First (To.Clients); begin -- Dispatch_One makes the connection between the common implementation -- and the generics while Has_Element (Iter) loop declare Client : constant Subscriber_Access := Element (Iter); begin Client.Receive_Event (Item); end; Iter := Next (Iter); end loop; end Post; -- ----------------------- -- Subscribe to events sent on the event channel. -- ----------------------- procedure Subscribe (To : in out Channel; Client : in Subscriber_Access) is begin pragma Assert (Client /= null, "Client subscriber must not be null"); Append (To.Clients, Client); end Subscribe; -- ----------------------- -- Unsubscribe to events sent on the event channel. -- ----------------------- procedure Unsubscribe (To : in out Channel; Client : in Subscriber_Access) is Iter : Cursor := First (To.Clients); begin while Has_Element (Iter) loop if Element (Iter) = Client then Delete (To.Clients, Iter); return; end if; Iter := Next (Iter); end loop; end Unsubscribe; -- ----------------------- -- Create an event channel with the given name. The type of channel -- is controlled by <b>Kind</b>. -- ----------------------- function Create (Name : String; Kind : String) return Channel_Access is begin for I in Factory'Range loop if Factory (I).Name.all = Kind then return Factory (I).Creator (Name); end if; end loop; return Create_Direct_Channel (Name); end Create; -- ----------------------- -- Create an event channel that post the event immediately. -- ----------------------- function Create_Direct_Channel (Name : String) return Channel_Access is Result : constant Channel_Access := new Channel; begin Result.Name := To_Unbounded_String (Name); return Result; end Create_Direct_Channel; end Util.Events.Channels;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6b03d2254583a63aa53e2fb7944578382465185c
regtests/ado-sequences-tests.adb
regtests/ado-sequences-tests.adb
----------------------------------------------------------------------- -- 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 ADO.Statements; with Regtests.Simple.Model; with ADO.Sequences.Hilo; with ADO.Sessions.Sources; with ADO.Sessions.Factory; with ADO.Schemas; 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; SEQUENCE_NAME : aliased constant String := "sequence"; Sequence_Table : aliased ADO.Schemas.Class_Mapping := ADO.Schemas.Class_Mapping '(Count => 0, Table => SEQUENCE_NAME'Access, Members => <>); -- 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.Sessions.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; -- Erase the sequence entry used for the allocate entity table. declare S : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; D : ADO.Statements.Delete_Statement := S.Create_Statement (Sequence_Table'Access); begin D.Set_Filter ("name = :name"); D.Bind_Param ("name", String '("allocate")); D.Execute; -- Also delete all allocate items. D := S.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); D.Execute; end; -- Create new objects. This forces the creation of a new entry in the sequence table. for I in 1 .. 1_00 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.Configs; with ADO.Sessions; with ADO.SQL; with ADO.Statements; with Regtests.Simple.Model; with ADO.Sequences.Hilo; with ADO.Sessions.Sources; with ADO.Sessions.Factory; with ADO.Schemas; 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; SEQUENCE_NAME : aliased constant String := "sequence"; Sequence_Table : aliased ADO.Schemas.Class_Mapping := ADO.Schemas.Class_Mapping '(Count => 0, Table => SEQUENCE_NAME'Access, Members => <>); -- 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.Sessions.Connection_Error => null; -- Good! An exception is expected because the session factory is empty. end; -- Make a real connection. Controller.Set_Connection (ADO.Configs.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; -- Erase the sequence entry used for the allocate entity table. declare S : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; D : ADO.Statements.Delete_Statement := S.Create_Statement (Sequence_Table'Access); begin D.Set_Filter ("name = :name"); D.Bind_Param ("name", String '("allocate")); D.Execute; -- Also delete all allocate items. D := S.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); D.Execute; end; -- Create new objects. This forces the creation of a new entry in the sequence table. for I in 1 .. 1_00 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;
Use ADO.Configs.Get_Config
Use ADO.Configs.Get_Config
Ada
apache-2.0
stcarrez/ada-ado
daa0773dfbf5783a73e939445ff38621222f4806
src/asf-components-utils-escapes.adb
src/asf-components-utils-escapes.adb
----------------------------------------------------------------------- -- components-utils-escape -- Escape generated content produced by component children -- 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.Strings.Transforms; package body ASF.Components.Utils.Escapes is -- ------------------------------ -- Write the content that was collected by rendering the inner children. -- Escape the content using Javascript escape rules. -- ------------------------------ procedure Write_Content (UI : in UIEscape; Writer : in out Contexts.Writer.Response_Writer'Class; Content : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI, Context); Result : Ada.Strings.Unbounded.Unbounded_String; begin Util.Strings.Transforms.Escape_Java (Content => Content, Into => Result); Writer.Write (Result); end Write_Content; -- ------------------------------ -- Encode the children components in the javascript queue. -- ------------------------------ overriding procedure Encode_Children (UI : in UIEscape; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin UIEscape'Class (UI).Write_Content (Writer.all, Content, Context); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; end ASF.Components.Utils.Escapes;
----------------------------------------------------------------------- -- components-utils-escape -- Escape generated content produced by component children -- Copyright (C) 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; package body ASF.Components.Utils.Escapes is -- ------------------------------ -- Write the content that was collected by rendering the inner children. -- Escape the content using Javascript escape rules. -- ------------------------------ procedure Write_Content (UI : in UIEscape; Writer : in out Contexts.Writer.Response_Writer'Class; Content : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI, Context); Result : Ada.Strings.Unbounded.Unbounded_String; Mode : constant String := UI.Get_Attribute (ESCAPE_MODE_NAME, Context); begin if Mode = "xml" then Util.Strings.Transforms.Escape_Xml (Content => Content, Into => Result); else Util.Strings.Transforms.Escape_Java (Content => Content, Into => Result); end if; Writer.Write (Result); end Write_Content; -- ------------------------------ -- Encode the children components in the javascript queue. -- ------------------------------ overriding procedure Encode_Children (UI : in UIEscape; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin UIEscape'Class (UI).Write_Content (Writer.all, Content, Context); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; end ASF.Components.Utils.Escapes;
Add support to escape using XML or using Javascript escape rules
Add support to escape using XML or using Javascript escape rules
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
716113d4d9e4ff13e4913d4a8da00ebd0bf0b765
src/ado-queries.adb
src/ado-queries.adb
----------------------------------------------------------------------- -- ado-queries -- 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 ADO.Queries.Loaders; package body ADO.Queries is -- ------------------------------ -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. -- ------------------------------ procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access) is begin Into.Query_Def := Query; Into.Is_Count := False; end Set_Query; -- ------------------------------ -- Set the query definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. -- ------------------------------ procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access) is begin Into.Query_Def := Query; Into.Is_Count := True; end Set_Count_Query; procedure Set_Query (Into : in out Context; Name : in String) is begin Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name); end Set_Query; -- ------------------------------ -- Set the limit for the SQL query. -- ------------------------------ procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural) is begin Into.First := First; Into.Last := Last; end Set_Limit; -- ------------------------------ -- Get the first row index. -- ------------------------------ function Get_First_Row_Index (From : in Context) return Natural is begin return From.First; end Get_First_Row_Index; -- ------------------------------ -- Get the last row index. -- ------------------------------ function Get_Last_Row_Index (From : in Context) return Natural is begin return From.Last_Index; end Get_Last_Row_Index; -- ------------------------------ -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. -- ------------------------------ function Get_Max_Row_Count (From : in Context) return Natural is begin return From.Max_Row_Count; end Get_Max_Row_Count; -- ------------------------------ -- Get the SQL query that correspond to the query context. -- ------------------------------ function Get_SQL (From : in Context; Driver : in ADO.Drivers.Driver_Index) return String is begin if From.Query_Def = null then return ""; else return Get_SQL (From.Query_Def, Driver, From.Is_Count); end if; end Get_SQL; -- ------------------------------ -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none -- ------------------------------ function Find_Query (File : in Query_File; Name : in String) return Query_Definition_Access is Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; return null; end Find_Query; function Get_SQL (From : in Query_Definition_Access; Driver : in ADO.Drivers.Driver_Index; Use_Count : in Boolean) return String is Query : Query_Info_Ref.Ref; begin ADO.Queries.Loaders.Read_Query (From); Query := From.Query.Get; if Query.Is_Null then return ""; end if; if Use_Count then if Length (Query.Value.Count_Query (Driver).SQL) > 0 then return To_String (Query.Value.Count_Query (Driver).SQL); else return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL); end if; elsif Length (Query.Value.Main_Query (Driver).SQL) > 0 then return To_String (Query.Value.Main_Query (Driver).SQL); else return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL); end if; end Get_SQL; end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- 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 ADO.Queries.Loaders; package body ADO.Queries is -- ------------------------------ -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. -- ------------------------------ procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access) is begin Into.Query_Def := Query; Into.Is_Count := False; end Set_Query; -- ------------------------------ -- Set the query definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. -- ------------------------------ procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access) is begin Into.Query_Def := Query; Into.Is_Count := True; end Set_Count_Query; procedure Set_Query (Into : in out Context; Name : in String) is begin Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name); end Set_Query; -- ------------------------------ -- Set the limit for the SQL query. -- ------------------------------ procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural) is begin Into.First := First; Into.Last := Last; end Set_Limit; -- ------------------------------ -- Get the first row index. -- ------------------------------ function Get_First_Row_Index (From : in Context) return Natural is begin return From.First; end Get_First_Row_Index; -- ------------------------------ -- Get the last row index. -- ------------------------------ function Get_Last_Row_Index (From : in Context) return Natural is begin return From.Last; end Get_Last_Row_Index; -- ------------------------------ -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. -- ------------------------------ function Get_Max_Row_Count (From : in Context) return Natural is begin return From.Max_Row_Count; end Get_Max_Row_Count; -- ------------------------------ -- Get the SQL query that correspond to the query context. -- ------------------------------ function Get_SQL (From : in Context; Driver : in ADO.Drivers.Driver_Index) return String is begin if From.Query_Def = null then return ""; else return Get_SQL (From.Query_Def, Driver, From.Is_Count); end if; end Get_SQL; -- ------------------------------ -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none -- ------------------------------ function Find_Query (File : in Query_File; Name : in String) return Query_Definition_Access is Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; return null; end Find_Query; function Get_SQL (From : in Query_Definition_Access; Driver : in ADO.Drivers.Driver_Index; Use_Count : in Boolean) return String is Query : Query_Info_Ref.Ref; begin ADO.Queries.Loaders.Read_Query (From); Query := From.Query.Get; if Query.Is_Null then return ""; end if; if Use_Count then if Length (Query.Value.Count_Query (Driver).SQL) > 0 then return To_String (Query.Value.Count_Query (Driver).SQL); else return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL); end if; elsif Length (Query.Value.Main_Query (Driver).SQL) > 0 then return To_String (Query.Value.Main_Query (Driver).SQL); else return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL); end if; end Get_SQL; end ADO.Queries;
Fix Get_Last_Row_Index function
Fix Get_Last_Row_Index function
Ada
apache-2.0
stcarrez/ada-ado
4bec13622f24122b8ff70fcb75bea338dfa1c11a
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "54"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "60"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Bump major version for web interface
Bump major version for web interface I'm not ready to release yet. I want to see if we can detect which build phase failed and I need to do an extended test.
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
bbe33f183c73e1ef38359265908aa40814d60e79
src/port_specification-transform.adb
src/port_specification-transform.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Utilities; with Ada.Characters.Latin_1; package body Port_Specification.Transform is package UTL renames Utilities; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- apply_directives -------------------------------------------------------------------------------------------- procedure apply_directives (specs : in out Portspecs) is procedure copy_option_over (position : option_crate.Cursor); procedure copy_option_over (position : option_crate.Cursor) is procedure augment (field : spec_option; directive : string_crate.Vector); rec : Option_Helper renames option_crate.Element (position); procedure augment (field : spec_option; directive : string_crate.Vector) is procedure transfer (position : string_crate.Cursor); procedure transfer (position : string_crate.Cursor) is item : HT.Text renames string_crate.Element (position); itemstr : String := HT.USS (item); special : HT.Text; begin case field is when build_depends_on => specs.build_deps.Append (item); when build_target_on => specs.build_target.Append (item); when cflags_on => specs.cflags.Append (item); when cmake_args_on | cmake_args_off => specs.cmake_args.Append (item); when configure_args_on | configure_args_off => specs.config_args.Append (item); when configure_env_on => specs.config_env.Append (item); when cppflags_on => specs.cppflags.Append (item); when cxxflags_on => specs.cxxflags.Append (item); when df_index_on => specs.df_index.Append (item); when extract_only => specs.extract_only.Append (item); when install_target_on => specs.install_tgt.Append (item); when keywords_on => specs.keywords.Append (item); when ldflags_on => specs.ldflags.Append (item); when lib_depends_on => specs.lib_deps.Append (item); when make_args_on => specs.make_args.Append (item); when make_env_on => specs.make_env.Append (item); when patchfiles_on => specs.patchfiles.Append (item); when run_depends_on => specs.run_deps.Append (item); when sub_files_on => specs.sub_files.Append (item); when sub_list_on => specs.sub_list.Append (item); when uses_on => specs.uses.Append (item); when qmake_off | qmake_on => specs.qmake_args.Append (item); when others => null; end case; if rec.currently_set_ON then case field is when cmake_bool_f_both => special := HT.SUS ("-D" & itemstr & ":BOOL=false"); specs.cmake_args.Append (special); when cmake_bool_t_both => special := HT.SUS ("-D" & itemstr & ":BOOL-true"); specs.cmake_args.Append (special); when configure_enable_both => special := HT.SUS ("--enable-" & itemstr); specs.config_args.Append (special); when configure_with_both => special := HT.SUS ("--with-" & itemstr); specs.config_args.Append (special); when others => null; end case; else case field is when cmake_bool_f_both => special := HT.SUS ("-D" & itemstr & ":BOOL-true"); specs.cmake_args.Append (special); when cmake_bool_t_both => special := HT.SUS ("-D" & itemstr & ":BOOL=false"); specs.cmake_args.Append (special); when configure_enable_both => special := HT.SUS ("--disable-" & itemstr); specs.config_args.Append (special); when configure_with_both => special := HT.SUS ("--without-" & itemstr); specs.config_args.Append (special); when others => null; end case; end if; end transfer; begin directive.Iterate (Process => transfer'Access); end augment; begin if rec.currently_set_ON then -- TODO BROKEN_ON augment (build_depends_on, rec.BUILD_DEPENDS_ON); augment (build_target_on, rec.BUILD_TARGET_ON); augment (cflags_on, rec.CFLAGS_ON); augment (cmake_args_on, rec.CMAKE_ARGS_ON); augment (configure_args_on, rec.CONFIGURE_ARGS_ON); augment (configure_args_on, rec.CONFIGURE_ENV_ON); augment (cppflags_on, rec.CPPFLAGS_ON); augment (cxxflags_on, rec.CXXFLAGS_ON); augment (df_index_on, rec.DF_INDEX_ON); -- -- EXTRA_PATCHES -- -- GH stuff (rethink) augment (install_target_on, rec.INSTALL_TARGET_ON); augment (keywords_on, rec.KEYWORDS_ON); augment (ldflags_on, rec.LDFLAGS_ON); augment (lib_depends_on, rec.LIB_DEPENDS_ON); augment (make_args_on, rec.MAKE_ARGS_ON); augment (make_env_on, rec.MAKE_ENV_ON); augment (patchfiles_on, rec.PATCHFILES_ON); augment (qmake_on, rec.QMAKE_ON); augment (run_depends_on, rec.RUN_DEPENDS_ON); augment (sub_files_on, rec.SUB_FILES_ON); augment (sub_list_on, rec.SUB_LIST_ON); -- -- test-target on augment (uses_on, rec.USES_ON); else augment (cmake_args_off, rec.CMAKE_ARGS_OFF); augment (configure_args_off, rec.CONFIGURE_ARGS_OFF); augment (qmake_off, rec.QMAKE_OFF); end if; augment (cmake_bool_f_both, rec.CMAKE_BOOL_F_BOTH); augment (cmake_bool_t_both, rec.CMAKE_BOOL_T_BOTH); augment (configure_enable_both, rec.CONFIGURE_ENABLE_BOTH); augment (configure_with_both, rec.CONFIGURE_WITH_BOTH); end copy_option_over; begin specs.ops_helpers.Iterate (Process => copy_option_over'Access); end apply_directives; -------------------------------------------------------------------------------------------- -- set_option_defaults -------------------------------------------------------------------------------------------- procedure set_option_defaults (specs : in out Portspecs; variant : String; opsys : supported_opsys; arch_standard : supported_arch; osrelease : String) is procedure vopt_set (position : string_crate.Cursor); procedure varstd_set (position : string_crate.Cursor); procedure opsys_set (position : string_crate.Cursor); procedure set_on (Key : HT.Text; Element : in out Option_Helper); variant_text : HT.Text := HT.SUS (variant); all_text : HT.Text := HT.SUS (options_all); arch_text : HT.Text := HT.SUS (UTL.cpu_arch (arch_standard)); opsys_text : HT.Text := HT.SUS (UTL.lower_opsys (opsys)); procedure set_on (Key : HT.Text; Element : in out Option_Helper) is begin Element.set_ON_by_default := True; end set_on; procedure vopt_set (position : string_crate.Cursor) is -- ignore =OFF versions (defaults already to False, only consider =ON item : String := HT.USS (string_crate.Element (position)); begin if HT.trails (item, "=ON") then declare option_name : String := HT.partial_search (item, 0, "="); option_text : HT.Text := HT.SUS (option_name); begin if specs.ops_helpers.Contains (option_text) then specs.ops_helpers.Update_Element (Position => specs.ops_helpers.Find (option_text), Process => set_on'Access); end if; end; end if; end vopt_set; procedure varstd_set (position : string_crate.Cursor) is option_name : String := HT.USS (string_crate.Element (position)); option_text : HT.Text := HT.SUS (option_name); begin if specs.ops_helpers.Contains (option_text) then specs.ops_helpers.Update_Element (Position => specs.ops_helpers.Find (option_text), Process => set_on'Access); end if; end varstd_set; procedure opsys_set (position : string_crate.Cursor) is -- Assume option name is valid option_name : String := HT.USS (string_crate.Element (position)); option_text : HT.Text; num_slash : Natural := HT.count_char (option_name, LAT.Solidus); begin if num_slash > 0 then if num_slash = 1 then declare opt_name : HT.Text := HT.SUS (HT.part_1 (option_name, "/")); spec_version : String := HT.part_2 (option_name, "/"); begin if GTE (gen_major => osrelease, spec_major => spec_version) then option_text := opt_name; end if; end; else declare opt_name : HT.Text := HT.SUS (HT.part_1 (option_name, "/")); temp_P2 : String := HT.part_2 (option_name, "/"); spec_version : String := HT.part_1 (temp_P2); arch_str : String := HT.part_2 (temp_P2); meets_ver : Boolean := spec_version = "" or else GTE (osrelease, spec_version); meets_arch : Boolean := HT.contains (arch_str, UTL.cpu_arch (arch_standard)); begin if meets_ver and then meets_arch then option_text := opt_name; end if; end; end if; else option_text := HT.SUS (option_name); end if; if specs.ops_helpers.Contains (option_text) then specs.ops_helpers.Update_Element (Position => specs.ops_helpers.Find (option_text), Process => set_on'Access); end if; end opsys_set; begin if variant = variant_standard then if specs.options_on.Contains (all_text) then specs.options_on.Element (all_text).list.Iterate (Process => varstd_set'Access); end if; if specs.options_on.Contains (arch_text) then specs.options_on.Element (arch_text).list.Iterate (Process => varstd_set'Access); end if; if specs.options_on.Contains (opsys_text) then specs.options_on.Element (opsys_text).list.Iterate (Process => opsys_set'Access); end if; else if not specs.variantopts.Contains (variant_text) then -- Variant does not exist, silently exit return; end if; specs.variantopts.Element (variant_text).list.Iterate (Process => vopt_set'Access); end if; end set_option_defaults; -------------------------------------------------------------------------------------------- -- set_option_to_default_values -------------------------------------------------------------------------------------------- procedure set_option_to_default_values (specs : in out Portspecs) is procedure copy_setting (position : option_crate.Cursor); procedure copy_setting (position : option_crate.Cursor) is procedure set_option (Key : HT.Text; Element : in out Option_Helper); procedure set_option (Key : HT.Text; Element : in out Option_Helper) is begin Element.currently_set_ON := Element.set_ON_by_default; end set_option; begin specs.ops_helpers.Update_Element (Position => position, Process => set_option'Access); end copy_setting; begin specs.ops_helpers.Iterate (Process => copy_setting'Access); end set_option_to_default_values; -------------------------------------------------------------------------------------------- -- release_format -------------------------------------------------------------------------------------------- function release_format (candidate : String) return Boolean is fullstop : Boolean := False; begin for X in candidate'Range loop case candidate (X) is when '.' => if fullstop then return False; end if; if X = candidate'First or else X = candidate'Last then return False; end if; fullstop := True; when '0' .. '9' => null; when others => return False; end case; end loop; return True; end release_format; -------------------------------------------------------------------------------------------- -- centurian_release -------------------------------------------------------------------------------------------- function centurian_release (release : String) return Natural is -- Requires release is validated by release_format() X : String := HT.part_1 (release, "."); Y : String := HT.part_2 (release, "."); RX : Natural := Integer'Value (X) * 100; RY : Natural := 0; begin if Y = "" then RY := Integer'Value (Y); end if; return (RX + RY); end centurian_release; -------------------------------------------------------------------------------------------- -- LTE -------------------------------------------------------------------------------------------- function LTE (gen_major, spec_major : String) return Boolean is GR : Natural := 999900; SR : Natural := 0; begin if release_format (gen_major) then GR := centurian_release (gen_major); end if; if release_format (spec_major) then SR := centurian_release (spec_major); end if; return (GR <= SR); end LTE; -------------------------------------------------------------------------------------------- -- GTE -------------------------------------------------------------------------------------------- function GTE (gen_major, spec_major : String) return Boolean is GR : Natural := 0; SR : Natural := 999900; begin if release_format (gen_major) then GR := centurian_release (gen_major); end if; if release_format (spec_major) then SR := centurian_release (spec_major); end if; return (GR >= SR); end GTE; end Port_Specification.Transform;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Utilities; with Ada.Characters.Latin_1; package body Port_Specification.Transform is package UTL renames Utilities; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- apply_directives -------------------------------------------------------------------------------------------- procedure apply_directives (specs : in out Portspecs) is procedure copy_option_over (position : option_crate.Cursor); procedure copy_option_over (position : option_crate.Cursor) is procedure augment (field : spec_option; directive : string_crate.Vector); procedure handle_broken; rec : Option_Helper renames option_crate.Element (position); procedure augment (field : spec_option; directive : string_crate.Vector) is procedure transfer (position : string_crate.Cursor); procedure transfer (position : string_crate.Cursor) is item : HT.Text renames string_crate.Element (position); itemstr : String := HT.USS (item); special : HT.Text; begin case field is when build_depends_on => specs.build_deps.Append (item); when build_target_on => specs.build_target.Append (item); when cflags_on => specs.cflags.Append (item); when cmake_args_on | cmake_args_off => specs.cmake_args.Append (item); when configure_args_on | configure_args_off => specs.config_args.Append (item); when configure_env_on => specs.config_env.Append (item); when cppflags_on => specs.cppflags.Append (item); when cxxflags_on => specs.cxxflags.Append (item); when df_index_on => specs.df_index.Append (item); when extract_only => specs.extract_only.Append (item); when install_target_on => specs.install_tgt.Append (item); when keywords_on => specs.keywords.Append (item); when ldflags_on => specs.ldflags.Append (item); when lib_depends_on => specs.lib_deps.Append (item); when make_args_on => specs.make_args.Append (item); when make_env_on => specs.make_env.Append (item); when patchfiles_on => specs.patchfiles.Append (item); when run_depends_on => specs.run_deps.Append (item); when sub_files_on => specs.sub_files.Append (item); when sub_list_on => specs.sub_list.Append (item); when uses_on => specs.uses.Append (item); when qmake_off | qmake_on => specs.qmake_args.Append (item); when others => null; end case; if rec.currently_set_ON then case field is when cmake_bool_f_both => special := HT.SUS ("-D" & itemstr & ":BOOL=false"); specs.cmake_args.Append (special); when cmake_bool_t_both => special := HT.SUS ("-D" & itemstr & ":BOOL-true"); specs.cmake_args.Append (special); when configure_enable_both => special := HT.SUS ("--enable-" & itemstr); specs.config_args.Append (special); when configure_with_both => special := HT.SUS ("--with-" & itemstr); specs.config_args.Append (special); when others => null; end case; else case field is when cmake_bool_f_both => special := HT.SUS ("-D" & itemstr & ":BOOL-true"); specs.cmake_args.Append (special); when cmake_bool_t_both => special := HT.SUS ("-D" & itemstr & ":BOOL=false"); specs.cmake_args.Append (special); when configure_enable_both => special := HT.SUS ("--disable-" & itemstr); specs.config_args.Append (special); when configure_with_both => special := HT.SUS ("--without-" & itemstr); specs.config_args.Append (special); when others => null; end case; end if; end transfer; begin directive.Iterate (Process => transfer'Access); end augment; procedure handle_broken is procedure grow (Key : HT.Text; Element : in out group_list); index : HT.Text := HT.SUS (broken_all); procedure grow (Key : HT.Text; Element : in out group_list) is begin Element.list.Append (rec.BROKEN_ON); end grow; begin if not HT.IsBlank (rec.BROKEN_ON) then if not specs.broken.Contains (index) then specs.establish_group (sp_broken, broken_all); end if; specs.broken.Update_Element (Position => specs.broken.Find (index), Process => grow'Access); end if; end handle_broken; begin if rec.currently_set_ON then handle_broken; augment (build_depends_on, rec.BUILD_DEPENDS_ON); augment (build_target_on, rec.BUILD_TARGET_ON); augment (cflags_on, rec.CFLAGS_ON); augment (cmake_args_on, rec.CMAKE_ARGS_ON); augment (configure_args_on, rec.CONFIGURE_ARGS_ON); augment (configure_args_on, rec.CONFIGURE_ENV_ON); augment (cppflags_on, rec.CPPFLAGS_ON); augment (cxxflags_on, rec.CXXFLAGS_ON); augment (df_index_on, rec.DF_INDEX_ON); -- -- EXTRA_PATCHES -- -- GH stuff (rethink) augment (install_target_on, rec.INSTALL_TARGET_ON); augment (keywords_on, rec.KEYWORDS_ON); augment (ldflags_on, rec.LDFLAGS_ON); augment (lib_depends_on, rec.LIB_DEPENDS_ON); augment (make_args_on, rec.MAKE_ARGS_ON); augment (make_env_on, rec.MAKE_ENV_ON); augment (patchfiles_on, rec.PATCHFILES_ON); augment (qmake_on, rec.QMAKE_ON); augment (run_depends_on, rec.RUN_DEPENDS_ON); augment (sub_files_on, rec.SUB_FILES_ON); augment (sub_list_on, rec.SUB_LIST_ON); -- -- test-target on augment (uses_on, rec.USES_ON); else augment (cmake_args_off, rec.CMAKE_ARGS_OFF); augment (configure_args_off, rec.CONFIGURE_ARGS_OFF); augment (qmake_off, rec.QMAKE_OFF); end if; augment (cmake_bool_f_both, rec.CMAKE_BOOL_F_BOTH); augment (cmake_bool_t_both, rec.CMAKE_BOOL_T_BOTH); augment (configure_enable_both, rec.CONFIGURE_ENABLE_BOTH); augment (configure_with_both, rec.CONFIGURE_WITH_BOTH); end copy_option_over; begin specs.ops_helpers.Iterate (Process => copy_option_over'Access); end apply_directives; -------------------------------------------------------------------------------------------- -- set_option_defaults -------------------------------------------------------------------------------------------- procedure set_option_defaults (specs : in out Portspecs; variant : String; opsys : supported_opsys; arch_standard : supported_arch; osrelease : String) is procedure vopt_set (position : string_crate.Cursor); procedure varstd_set (position : string_crate.Cursor); procedure opsys_set (position : string_crate.Cursor); procedure set_on (Key : HT.Text; Element : in out Option_Helper); variant_text : HT.Text := HT.SUS (variant); all_text : HT.Text := HT.SUS (options_all); arch_text : HT.Text := HT.SUS (UTL.cpu_arch (arch_standard)); opsys_text : HT.Text := HT.SUS (UTL.lower_opsys (opsys)); procedure set_on (Key : HT.Text; Element : in out Option_Helper) is begin Element.set_ON_by_default := True; end set_on; procedure vopt_set (position : string_crate.Cursor) is -- ignore =OFF versions (defaults already to False, only consider =ON item : String := HT.USS (string_crate.Element (position)); begin if HT.trails (item, "=ON") then declare option_name : String := HT.partial_search (item, 0, "="); option_text : HT.Text := HT.SUS (option_name); begin if specs.ops_helpers.Contains (option_text) then specs.ops_helpers.Update_Element (Position => specs.ops_helpers.Find (option_text), Process => set_on'Access); end if; end; end if; end vopt_set; procedure varstd_set (position : string_crate.Cursor) is option_name : String := HT.USS (string_crate.Element (position)); option_text : HT.Text := HT.SUS (option_name); begin if specs.ops_helpers.Contains (option_text) then specs.ops_helpers.Update_Element (Position => specs.ops_helpers.Find (option_text), Process => set_on'Access); end if; end varstd_set; procedure opsys_set (position : string_crate.Cursor) is -- Assume option name is valid option_name : String := HT.USS (string_crate.Element (position)); option_text : HT.Text; num_slash : Natural := HT.count_char (option_name, LAT.Solidus); begin if num_slash > 0 then if num_slash = 1 then declare opt_name : HT.Text := HT.SUS (HT.part_1 (option_name, "/")); spec_version : String := HT.part_2 (option_name, "/"); begin if GTE (gen_major => osrelease, spec_major => spec_version) then option_text := opt_name; end if; end; else declare opt_name : HT.Text := HT.SUS (HT.part_1 (option_name, "/")); temp_P2 : String := HT.part_2 (option_name, "/"); spec_version : String := HT.part_1 (temp_P2); arch_str : String := HT.part_2 (temp_P2); meets_ver : Boolean := spec_version = "" or else GTE (osrelease, spec_version); meets_arch : Boolean := HT.contains (arch_str, UTL.cpu_arch (arch_standard)); begin if meets_ver and then meets_arch then option_text := opt_name; end if; end; end if; else option_text := HT.SUS (option_name); end if; if specs.ops_helpers.Contains (option_text) then specs.ops_helpers.Update_Element (Position => specs.ops_helpers.Find (option_text), Process => set_on'Access); end if; end opsys_set; begin if variant = variant_standard then if specs.options_on.Contains (all_text) then specs.options_on.Element (all_text).list.Iterate (Process => varstd_set'Access); end if; if specs.options_on.Contains (arch_text) then specs.options_on.Element (arch_text).list.Iterate (Process => varstd_set'Access); end if; if specs.options_on.Contains (opsys_text) then specs.options_on.Element (opsys_text).list.Iterate (Process => opsys_set'Access); end if; else if not specs.variantopts.Contains (variant_text) then -- Variant does not exist, silently exit return; end if; specs.variantopts.Element (variant_text).list.Iterate (Process => vopt_set'Access); end if; end set_option_defaults; -------------------------------------------------------------------------------------------- -- set_option_to_default_values -------------------------------------------------------------------------------------------- procedure set_option_to_default_values (specs : in out Portspecs) is procedure copy_setting (position : option_crate.Cursor); procedure copy_setting (position : option_crate.Cursor) is procedure set_option (Key : HT.Text; Element : in out Option_Helper); procedure set_option (Key : HT.Text; Element : in out Option_Helper) is begin Element.currently_set_ON := Element.set_ON_by_default; end set_option; begin specs.ops_helpers.Update_Element (Position => position, Process => set_option'Access); end copy_setting; begin specs.ops_helpers.Iterate (Process => copy_setting'Access); end set_option_to_default_values; -------------------------------------------------------------------------------------------- -- release_format -------------------------------------------------------------------------------------------- function release_format (candidate : String) return Boolean is fullstop : Boolean := False; begin for X in candidate'Range loop case candidate (X) is when '.' => if fullstop then return False; end if; if X = candidate'First or else X = candidate'Last then return False; end if; fullstop := True; when '0' .. '9' => null; when others => return False; end case; end loop; return True; end release_format; -------------------------------------------------------------------------------------------- -- centurian_release -------------------------------------------------------------------------------------------- function centurian_release (release : String) return Natural is -- Requires release is validated by release_format() X : String := HT.part_1 (release, "."); Y : String := HT.part_2 (release, "."); RX : Natural := Integer'Value (X) * 100; RY : Natural := 0; begin if Y = "" then RY := Integer'Value (Y); end if; return (RX + RY); end centurian_release; -------------------------------------------------------------------------------------------- -- LTE -------------------------------------------------------------------------------------------- function LTE (gen_major, spec_major : String) return Boolean is GR : Natural := 999900; SR : Natural := 0; begin if release_format (gen_major) then GR := centurian_release (gen_major); end if; if release_format (spec_major) then SR := centurian_release (spec_major); end if; return (GR <= SR); end LTE; -------------------------------------------------------------------------------------------- -- GTE -------------------------------------------------------------------------------------------- function GTE (gen_major, spec_major : String) return Boolean is GR : Natural := 0; SR : Natural := 999900; begin if release_format (gen_major) then GR := centurian_release (gen_major); end if; if release_format (spec_major) then SR := centurian_release (spec_major); end if; return (GR >= SR); end GTE; end Port_Specification.Transform;
Add [option].BROKEN_ON support
Add [option].BROKEN_ON support
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
dd94f8679651501a44098b6628661777c859d436
src/security-policies-urls.adb
src/security-policies-urls.adb
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ overriding procedure Finish_Config (Into : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; package body Security.Policies.Urls is -- ------------------------------ -- URL policy -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : URL_Policy_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
Remove Finish_Config
Remove Finish_Config
Ada
apache-2.0
stcarrez/ada-security
be79cf942d7cbadc7aca6d101128190459ab60ac
src/util-concurrent-arrays.ads
src/util-concurrent-arrays.ads
----------------------------------------------------------------------- -- 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.Finalization; with Util.Concurrent.Counters; -- The <b>Util.Concurrent.Vectors</b> generic package defines a vector which provides a -- concurrent read only access and a protected exclusive write access. This implementation -- is intended to be used in applications that have to frequently iterate over the vector -- content. Adding or removing elements in the vector is assumed to be a not so frequent -- operation. Based on these assumptions, updating the vector array is implemented by -- using the <tt>copy on write</tt> design pattern. Read access is provided through a -- reference object that can be shared by multiple readers. -- -- The vector instance is declared and elements are added as follows: -- -- C : Vector; -- -- C.Append (E1); -- -- To read and iterate over the vector, a task will get a reference to the vector array -- and it will iterate over it. The reference will be held until the reference object is -- finalized. While doing so, if another task updates the vector, a new vector array will -- be associated with the vector instance (but this will not change the reader's references). -- -- R : Ref := C.Get; -- -- R.Iterate (Process'Access); -- ... -- R.Iterate (Process'Access); -- -- In the above example, the two <b>Iterate</b> operations will iterate over the same list of -- elements, even if another task appends an element in the middle. -- -- Notes: -- o This package is close to the Java class <tt>java.util.concurrent.CopyOnWriteArrayList</tt>. -- o The package implements voluntarily a very small subset of Ada.Containers.Vectors. -- o The implementation does not use the Ada container for performance and size reasons. -- o The Iterate and Reverse_Iterate operation give a direct access to the element generic -- type Index_Type is range <>; type Element_Type is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; package Util.Concurrent.Arrays is -- The reference to the read-only vector elements. type Ref is tagged private; -- Returns True if the container is empty. function Is_Empty (Container : in Ref) return Boolean; -- 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)); -- 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)); -- Vector of elements. type Vector is new Ada.Finalization.Limited_Controlled with private; -- Get a read-only reference to the vector elements. The referenced vector will never -- be modified. function Get (Container : in Vector'Class) return Ref; -- 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); -- 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); -- Release the vector elements. overriding procedure Finalize (Object : in out Vector); private -- To store the vector elements, we use an array which is allocated dynamically. -- The generated code is smaller compared to the use of Ada vectors container. type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; type Vector_Record (Len : Positive) is record Ref_Counter : Util.Concurrent.Counters.Counter; List : Element_Array (1 .. Len); end record; type Vector_Record_Access is access all Vector_Record; type Ref is new Ada.Finalization.Controlled with record Target : Vector_Record_Access := null; end record; -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. overriding procedure Finalize (Obj : in out Ref); -- Update the reference counter after an assignment. overriding procedure Adjust (Obj : in out Ref); -- Vector of objects protected type Protected_Vector is -- Get a readonly reference to the vector. function Get return Ref; -- Append the element to the vector. procedure Append (Item : in Element_Type); -- Remove the element from the vector. procedure Remove (Item : in Element_Type); private Elements : Ref; -- Elements : Vector_Record_Access := null; end Protected_Vector; type Vector is new Ada.Finalization.Limited_Controlled with record List : Protected_Vector; end record; end Util.Concurrent.Arrays;
----------------------------------------------------------------------- -- 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.Finalization; with Util.Concurrent.Counters; -- == Introduction == -- The <b>Util.Concurrent.Arrays</b> generic package defines an array which provides a -- concurrent read only access and a protected exclusive write access. This implementation -- is intended to be used in applications that have to frequently iterate over the array -- content. Adding or removing elements in the array is assumed to be a not so frequent -- operation. Based on these assumptions, updating the array is implemented by -- using the <tt>copy on write</tt> design pattern. Read access is provided through a -- reference object that can be shared by multiple readers. -- -- == Declaration == -- The package must be instantiated using the element type representing the array element. -- -- package My_Array is new Util.Concurrent.Arrays (Element_Type => Integer); -- -- == Adding Elements == -- The vector instance is declared and elements are added as follows: -- -- C : My_Array.Vector; -- -- C.Append (E1); -- -- == Iterating over the array == -- To read and iterate over the vector, a task will get a reference to the vector array -- and it will iterate over it. The reference will be held until the reference object is -- finalized. While doing so, if another task updates the vector, a new vector array will -- be associated with the vector instance (but this will not change the reader's references). -- -- R : My_Array.Ref := C.Get; -- -- R.Iterate (Process'Access); -- ... -- R.Iterate (Process'Access); -- -- In the above example, the two `Iterate` operations will iterate over the same list of -- elements, even if another task appends an element in the middle. -- -- Notes: -- * This package is close to the Java class `java.util.concurrent.CopyOnWriteArrayList`. -- * The package implements voluntarily a very small subset of `Ada.Containers.Vectors`. -- * The implementation does not use the Ada container for performance and size reasons. -- * The `Iterate` and `Reverse_Iterate` operation give a direct access to the element. generic type Element_Type is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; package Util.Concurrent.Arrays is -- The reference to the read-only vector elements. type Ref is tagged private; -- Returns True if the container is empty. function Is_Empty (Container : in Ref) return Boolean; -- 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)); -- 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)); -- Vector of elements. type Vector is new Ada.Finalization.Limited_Controlled with private; -- Get a read-only reference to the vector elements. The referenced vector will never -- be modified. function Get (Container : in Vector'Class) return Ref; -- 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); -- 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); -- Release the vector elements. overriding procedure Finalize (Object : in out Vector); private -- To store the vector elements, we use an array which is allocated dynamically. -- The generated code is smaller compared to the use of Ada vectors container. type Element_Array is array (Positive range <>) of Element_Type; type Element_Array_Access is access all Element_Array; Null_Element_Array : constant Element_Array_Access := null; type Vector_Record (Len : Positive) is record Ref_Counter : Util.Concurrent.Counters.Counter; List : Element_Array (1 .. Len); end record; type Vector_Record_Access is access all Vector_Record; type Ref is new Ada.Finalization.Controlled with record Target : Vector_Record_Access := null; end record; -- Release the reference. Invoke <b>Finalize</b> and free the storage if it was -- the last reference. overriding procedure Finalize (Obj : in out Ref); -- Update the reference counter after an assignment. overriding procedure Adjust (Obj : in out Ref); -- Vector of objects protected type Protected_Vector is -- Get a readonly reference to the vector. function Get return Ref; -- Append the element to the vector. procedure Append (Item : in Element_Type); -- Remove the element from the vector. procedure Remove (Item : in Element_Type); private Elements : Ref; end Protected_Vector; type Vector is new Ada.Finalization.Limited_Controlled with record List : Protected_Vector; end record; end Util.Concurrent.Arrays;
Update the documentation to be extracted by dynamo
Update the documentation to be extracted by dynamo
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d4fa0b1b16b7bd3b374577be47f8a25ea1a9cf8c
samples/lzma_decrypt.adb
samples/lzma_decrypt.adb
----------------------------------------------------------------------- -- lzma_decrypt -- Decrypt and decompress file using Util.Streams.AES -- Copyright (C) 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Streams.Stream_IO; with Util.Streams.Files; with Util.Streams.AES; with Util.Streams.Buffered.Lzma; with Util.Encoders.AES; with Util.Encoders.KDF.PBKDF2_HMAC_SHA256; procedure Lzma_Decrypt is use Util.Encoders.KDF; procedure Decrypt_File (Source : in String; Destination : in String; Password : in String); procedure Decrypt_File (Source : in String; Destination : in String; Password : in String) is In_Stream : aliased Util.Streams.Files.File_Stream; Out_Stream : aliased Util.Streams.Files.File_Stream; Decompress : aliased Util.Streams.Buffered.Lzma.Decompress_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Password_Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create (Password); Salt : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("fake-salt"); Key : Util.Encoders.Secret_Key (Length => Util.Encoders.AES.AES_256_Length); begin -- Generate a derived key from the password. PBKDF2_HMAC_SHA256 (Password => Password_Key, Salt => Salt, Counter => 20000, Result => Key); -- Setup file -> input and cipher -> output file streams. In_Stream.Open (Ada.Streams.Stream_IO.In_File, Source); Out_Stream.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Destination); Decipher.Consumes (Input => In_Stream'Access, Size => 32768); Decipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); Decompress.Initialize (Input => Decipher'Access, Size => 32768); -- Copy input to output through the cipher. Util.Streams.Copy (From => Decompress, Into => Out_Stream); end Decrypt_File; begin if Ada.Command_Line.Argument_Count /= 3 then Ada.Text_IO.Put_Line ("Usage: decrypt source password destination"); return; end if; Decrypt_File (Source => Ada.Command_Line.Argument (1), Destination => Ada.Command_Line.Argument (3), Password => Ada.Command_Line.Argument (2)); end Lzma_Decrypt;
----------------------------------------------------------------------- -- lzma_decrypt -- Decrypt and decompress file using Util.Streams.AES -- Copyright (C) 2019, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Streams.Stream_IO; with Util.Streams.Files; with Util.Streams.AES; with Util.Streams.Buffered.Lzma; with Util.Encoders.AES; with Util.Encoders.KDF.PBKDF2_HMAC_SHA256; procedure Lzma_Decrypt is use Util.Encoders.KDF; procedure Decrypt_File (Source : in String; Destination : in String; Password : in String); procedure Decrypt_File (Source : in String; Destination : in String; Password : in String) is In_Stream : aliased Util.Streams.Files.File_Stream; Out_Stream : aliased Util.Streams.Files.File_Stream; Decompress : aliased Util.Streams.Buffered.Lzma.Decompress_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Password_Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create (Password); Salt : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("fake-salt"); Key : Util.Encoders.Secret_Key (Length => Util.Encoders.AES.AES_256_Length); begin -- Generate a derived key from the password. PBKDF2_HMAC_SHA256 (Password => Password_Key, Salt => Salt, Counter => 20000, Result => Key); -- Setup file -> input and cipher -> output file streams. In_Stream.Open (Ada.Streams.Stream_IO.In_File, Source); Out_Stream.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Destination); Decipher.Consumes (Input => In_Stream'Unchecked_Access, Size => 32768); Decipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); Decompress.Initialize (Input => Decipher'Unchecked_Access, Size => 32768); -- Copy input to output through the cipher. Util.Streams.Copy (From => Decompress, Into => Out_Stream); end Decrypt_File; begin if Ada.Command_Line.Argument_Count /= 3 then Ada.Text_IO.Put_Line ("Usage: decrypt source password destination"); return; end if; Decrypt_File (Source => Ada.Command_Line.Argument (1), Destination => Ada.Command_Line.Argument (3), Password => Ada.Command_Line.Argument (2)); end Lzma_Decrypt;
Fix wrong 'Access usage (it was correct with previous versions of the GNAT compiler\!)
Fix wrong 'Access usage (it was correct with previous versions of the GNAT compiler\!)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7fe605d8edc22f3be6728104474b359f5d83ddce
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply, "Blog post page is invalid" ); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("format", "dotclear"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("format", "dotclear"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "POST_PUBLISHED"); Request.Set_Parameter ("format", "dotclear"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Publish_Date; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply, "Blog post page is invalid" ); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("post-format", "dotclear"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "dotclear"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "POST_PUBLISHED"); Request.Set_Parameter ("format", "dotclear"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Publish_Date; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
Fix name of post-format parameter
Fix name of post-format parameter
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
135a22af10b173ed6dd10f456ec7e99b288b095d
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Column_Definition; Log : in out Util.Log.Logging'Class); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns true if the column is using a variable length (ex: a string). function Is_Variable_Length (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Set the column type. procedure Set_Type (Into : in out Column_Definition; Name : in String); -- Set the SQL length of the column. procedure Set_Sql_Length (Into : in out Column_Definition; Value : in String; Log : in out Util.Log.Logging'Class); -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; -- The number of <<PK>> columns found. Key_Count : Natural := 0; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; -- Whether the serialization operation have to be generated. Is_Serializable : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Table_Definition; Log : in out Util.Log.Logging'Class); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; Bean : Util.Beans.Objects.Object; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the column is auditable (generate code to track changes). Is_Auditable : Boolean := False; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Column_Definition; Log : in out Util.Log.Logging'Class); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns true if the column is using a variable length (ex: a string). function Is_Variable_Length (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Set the column type. procedure Set_Type (Into : in out Column_Definition; Name : in String); -- Set the SQL length of the column. procedure Set_Sql_Length (Into : in out Column_Definition; Value : in String; Log : in out Util.Log.Logging'Class); -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Parent_Name : Unbounded_String; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; -- The number of <<PK>> columns found. Key_Count : Natural := 0; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : Boolean := False; -- Whether the bean type is a limited type or not. Is_Limited : Boolean := False; -- Whether the serialization operation have to be generated. Is_Serializable : Boolean := False; -- Whether the table contains auditable fields. Is_Auditable : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Validate the definition by checking and reporting problems to the logger interface. overriding procedure Validate (Def : in out Table_Definition; Log : in out Util.Log.Logging'Class); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Add Is_Auditable member in the Table_Definition
Add Is_Auditable member in the Table_Definition
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
bc03717d21c2752d88fd8b7700929f798668a860
src/sys/http/util-http-mimes.ads
src/sys/http/util-http-mimes.ads
----------------------------------------------------------------------- -- util-http-mimes -- HTTP Headers -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package Util.Http.Mimes is subtype Mime_Access is Util.Strings.Name_Access; type Mime_List is array (Positive range <>) of Mime_Access; type Mime_List_Access is access constant Mime_List; Json : aliased constant String := "application/json"; Xml : aliased constant String := "application/xml"; Pdf : aliased constant String := "application/pdf"; Form : aliased constant String := "application/x-www-form-urlencoded"; Text : aliased constant String := "text/plain"; Html : aliased constant String := "text/html"; Css : aliased constant String := "text/css"; Js : aliased constant String := "text/javascript"; Png : aliased constant String := "image/png"; Jpg : aliased constant String := "image/jpeg"; Gif : aliased constant String := "image/gif"; Ico : aliased constant String := "image/x-icon"; Svg : aliased constant String := "image/svg+xml"; Octet : aliased constant String := "application/octet-stream"; -- List of mime types for images. Images : aliased constant Mime_List := (Jpg'Access, Png'Access, Gif'Access, Ico'Access, Svg'Access); -- List of mime types for HTTP responses. Api : aliased constant Mime_List := (Json'Access, Xml'Access); end Util.Http.Mimes;
----------------------------------------------------------------------- -- util-http-mimes -- HTTP Headers -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package Util.Http.Mimes is subtype Mime_Access is Util.Strings.Name_Access; type Mime_List is array (Positive range <>) of Mime_Access; type Mime_List_Access is access constant Mime_List; Json : aliased constant String := "application/json"; Xml : aliased constant String := "application/xml"; Pdf : aliased constant String := "application/pdf"; Form : aliased constant String := "application/x-www-form-urlencoded"; Text : aliased constant String := "text/plain"; Html : aliased constant String := "text/html"; Css : aliased constant String := "text/css"; Js : aliased constant String := "text/javascript"; Png : aliased constant String := "image/png"; Jpg : aliased constant String := "image/jpeg"; Gif : aliased constant String := "image/gif"; Ico : aliased constant String := "image/x-icon"; Svg : aliased constant String := "image/svg+xml"; Octet : aliased constant String := "application/octet-stream"; -- List of mime types for images. Images : aliased constant Mime_List := (Jpg'Access, Png'Access, Gif'Access, Ico'Access, Svg'Access); -- List of mime types for HTTP responses. Api : aliased constant Mime_List := (Json'Access, Xml'Access); -- Returns true if the Content-Type header uses the given mime type. -- The `Header` parameter is assumed to follow the media type specification -- with the pattern: -- type / subtype [; token = (token|quoted-string)] function Is_Mime (Header : in String; Mime : in String) return Boolean; end Util.Http.Mimes;
Declare the Is_Mime function
Declare the Is_Mime function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8fc30499c0c67d323f5d576dd6d41b264ae75076
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Util.Refs; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH; type Node_List_Ref is private; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)); -- Returns True if the list reference is empty. function Is_Empty (List : in Node_List_Ref) return Boolean; -- Get the number of nodes in the list. function Length (List : in Node_List_Ref) return Natural; private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited new Util.Refs.Ref_Entity with record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List); -- Append a node to the node list. -- procedure Append (Into : in out Node_List; -- Node : in Node_Type_Access); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); type Node_List_Ref is new Node_List_Refs.Ref with null record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2016, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; with Util.Refs; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_NEWLINE, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_NEWLINE; type Node_List_Ref is private; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; Parent : Node_Type_Access; when N_PREFORMAT => Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Append a node to the node list. procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)); -- Returns True if the list reference is empty. function Is_Empty (List : in Node_List_Ref) return Boolean; -- Get the number of nodes in the list. function Length (List : in Node_List_Ref) return Natural; private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited new Util.Refs.Ref_Entity with record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; -- Finalize the node list to release the allocated memory. overriding procedure Finalize (List : in out Node_List); -- Append a node to the node list. -- procedure Append (Into : in out Node_List; -- Node : in Node_Type_Access); package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access); type Node_List_Ref is new Node_List_Refs.Ref with null record; end Wiki.Nodes;
Add N_NEWLINE node to represent a newline in a document
Add N_NEWLINE node to represent a newline in a document
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
087024a2b250e8f812c813d6c89b1c2ddf504f23
src/wiki-nodes.ads
src/wiki-nodes.ads
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020, 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 Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_NONE, N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_LIST_ITEM_END, N_LIST_END, N_NUM_LIST_END, N_LIST_ITEM, N_NEWLINE, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_TABLE, N_ROW, N_COLUMN, N_LIST_START, N_NUM_LIST_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_NONE .. N_NEWLINE; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record Parent : Node_Type_Access; case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_TOC_ENTRY | N_NUM_LIST_START | N_LIST_START => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START | N_TABLE | N_ROW | N_COLUMN => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; when N_PREFORMAT => Language : Wiki.Strings.UString; Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Finalize the node list to release the allocated memory. procedure Finalize (List : in out Node_List); private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020, 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 Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_NONE, N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_LIST_ITEM_END, N_LIST_END, N_NUM_LIST_END, N_LIST_ITEM, N_END_DEFINITION, N_NEWLINE, N_HEADER, N_DEFINITION, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_TABLE, N_ROW, N_COLUMN, N_LIST_START, N_NUM_LIST_START, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_NONE .. N_NEWLINE; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record Parent : Node_Type_Access; case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_TOC_ENTRY | N_NUM_LIST_START | N_LIST_START | N_DEFINITION => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START | N_TABLE | N_ROW | N_COLUMN => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; when N_PREFORMAT => Language : Wiki.Strings.UString; Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Finalize the node list to release the allocated memory. procedure Finalize (List : in out Node_List); private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; end Wiki.Nodes;
Add N_DEFINITION and N_END_DEFINITION
Add N_DEFINITION and N_END_DEFINITION
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
de74d9c7ca46b447368e5c43dec0a0fa5ed9805c
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020, 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.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- === Wiki Renderer === -- The `Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; procedure Write_Optional_Space (Engine : in out Wiki_Renderer); -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Need_Newline : Boolean := False; Need_Space : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Natural := 0; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; In_Table : Boolean := False; Col_Index : Natural := 0; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; -- Render the table of content. procedure Render_TOC (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Level : in Natural); -- Render a table component such as N_TABLE. procedure Render_Table (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Render a table row component such as N_ROW. procedure Render_Row (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Render a table row component such as N_COLUMN. procedure Render_Column (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020, 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.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- === Wiki Renderer === -- The `Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; procedure Write_Optional_Space (Engine : in out Wiki_Renderer); -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer; Optional : in Boolean := False); procedure Need_Separator_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Need_Newline : Boolean := False; Need_Space : Boolean := False; Empty_Line : Boolean := True; Empty_Previous_Line : Boolean := True; Keep_Content : Natural := 0; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Html_Table : Boolean := False; In_Table : Boolean := False; Col_Index : Natural := 0; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; procedure Write_Link (Engine : in out Wiki_Renderer; Link : in Strings.WString); -- Render the table of content. procedure Render_TOC (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Level : in Natural); -- Render a table component such as N_TABLE. procedure Render_Table (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Render a table row component such as N_ROW. procedure Render_Row (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Render a table row component such as N_COLUMN. procedure Render_Column (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); end Wiki.Render.Wiki;
Declare the Write_Link procedure
Declare the Write_Link procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ec351371f083355aa6f1545cf4bacdd93fd7c77b
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); if Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Context_Path & View (View'First .. Pos - 1) & To_String (Handler.View_Ext); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Context_Path & View; end if; return Context_Path & View; end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is begin return Handler.Get_Action_URL (Context, View); end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); if Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Context_Path & View (View'First .. Pos - 1) & To_String (Handler.View_Ext); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Context_Path & View; end if; return Context_Path & View; end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
Fix get_Redirect_URL to handler view parameters
Fix get_Redirect_URL to handler view parameters
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
03a378abc2e50e571079ad4ebad9dff85a94c71d
src/asf-responses-mockup.adb
src/asf-responses-mockup.adb
----------------------------------------------------------------------- -- asf.responses -- ASF Requests -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ASF.Responses</b> package is an Ada implementation of -- the Java servlet response (JSR 315 5. The Response). package body ASF.Responses.Mockup is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin return Util.Strings.Maps.Has_Element (Pos); end Contains_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Resp.Headers.Iterate (Process => Process_Wrapper'Access); end Iterate_Headers; -- ------------------------------ -- Sets a response header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin Resp.Headers.Include (Name, Value); end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin Resp.Headers.Insert (Name, Value); end Add_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the response. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Resp : in Response; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else return ""; end if; end Get_Header; -- ------------------------------ -- Get the content written to the mockup output stream. -- ------------------------------ procedure Read_Content (Resp : in out Response; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Resp.Content.Read (Into => Into); end Read_Content; -- ------------------------------ -- Clear the response content. -- This operation removes any content held in the output stream, clears the status, -- removes any header in the response. -- ------------------------------ procedure Clear (Resp : in out Response) is Content : Ada.Strings.Unbounded.Unbounded_String; begin Resp.Read_Content (Content); Resp.Status := SC_OK; Resp.Headers.Clear; end Clear; -- ------------------------------ -- Initialize the response mockup output stream. -- ------------------------------ overriding procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (128 * 1024); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; end ASF.Responses.Mockup;
----------------------------------------------------------------------- -- asf.responses -- ASF Requests -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ASF.Responses</b> package is an Ada implementation of -- the Java servlet response (JSR 315 5. The Response). package body ASF.Responses.Mockup is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin return Util.Strings.Maps.Has_Element (Pos); end Contains_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Resp.Headers.Iterate (Process => Process_Wrapper'Access); end Iterate_Headers; -- ------------------------------ -- Sets a response header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin Resp.Headers.Include (Name, Value); end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin if Resp.Headers.Contains (Name) then Resp.Headers.Include (Name, Resp.Headers.Element (Name) & ASCII.LF & Name & ": " & Value); else Resp.Headers.Insert (Name, Value); end if; end Add_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the response. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Resp : in Response; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else return ""; end if; end Get_Header; -- ------------------------------ -- Get the content written to the mockup output stream. -- ------------------------------ procedure Read_Content (Resp : in out Response; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Resp.Content.Read (Into => Into); end Read_Content; -- ------------------------------ -- Clear the response content. -- This operation removes any content held in the output stream, clears the status, -- removes any header in the response. -- ------------------------------ procedure Clear (Resp : in out Response) is Content : Ada.Strings.Unbounded.Unbounded_String; begin Resp.Read_Content (Content); Resp.Status := SC_OK; Resp.Headers.Clear; end Clear; -- ------------------------------ -- Initialize the response mockup output stream. -- ------------------------------ overriding procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (128 * 1024); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; end ASF.Responses.Mockup;
Fix the response mockup to support several response headers with the same name
Fix the response mockup to support several response headers with the same name
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
1a0f24a624c1c17887bb190ef279bdde7e837dee
src/asf-sessions-factory.adb
src/asf-sessions-factory.adb
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- 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.Encoders.Base64; with Util.Log.Loggers; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package body ASF.Sessions.Factory is use Ada.Finalization; use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory"); -- ------------------------------ -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. -- ------------------------------ procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access) is use Ada.Streams; use Interfaces; Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1); Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size); Encoder : Util.Encoders.Base64.Encoder; Last : Stream_Element_Offset; Encoded : Stream_Element_Offset; begin Factory.Lock.Write; -- Generate the random sequence. for I in 0 .. Factory.Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Factory.Random); begin Rand (4 * I) := Stream_Element (Value and 16#0FF#); Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; Factory.Lock.Release_Write; -- Encode the random stream in base64 and save it into the Id string. Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); Id := new String (1 .. Natural (Encoded + 1)); for I in 0 .. Encoded loop Id (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; Log.Info ("Allocated session {0}", Id.all); end Allocate_Session_Id; -- ------------------------------ -- Create a new session -- ------------------------------ procedure Create_Session (Factory : in out Session_Factory; Result : out Session) is Sess : Session; Impl : constant Session_Record_Access := new Session_Record; begin Impl.Ref_Counter := Util.Concurrent.Counters.ONE; Impl.Create_Time := Ada.Calendar.Clock; Impl.Access_Time := Impl.Create_Time; Impl.Max_Inactive := Factory.Max_Inactive; Sess.Impl := Impl; Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id); Factory.Lock.Write; Factory.Sessions.Insert (Impl.Id.all'Access, Sess); Factory.Lock.Release_Write; Result := Sess; end Create_Session; -- ------------------------------ -- Deletes the session. -- ------------------------------ procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session) is begin null; end Delete_Session; -- ------------------------------ -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. -- ------------------------------ procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session) is begin Result := Null_Session; Factory.Lock.Read; declare Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access); begin if Session_Maps.Has_Element (Pos) then Result := Session_Maps.Element (Pos); end if; end; Factory.Lock.Release_Read; if Result.Is_Valid then Result.Impl.Access_Time := Ada.Calendar.Clock; Log.Info ("Found active session {0}", Id); else Log.Info ("Invalid session {0}", Id); end if; end Find_Session; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is begin return Factory.Max_Inactive; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration) is begin Factory.Max_Inactive := Interval; end Set_Max_Inactive_Interval; -- ------------------------------ -- Initialize the session factory. -- ------------------------------ overriding procedure Initialize (Factory : in out Session_Factory) is begin Id_Random.Reset (Factory.Random); end Initialize; end ASF.Sessions.Factory;
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base64; with Util.Log.Loggers; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package body ASF.Sessions.Factory is use Ada.Finalization; use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory"); -- ------------------------------ -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. -- ------------------------------ procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access) is use Ada.Streams; use Interfaces; Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1); Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size); Encoder : Util.Encoders.Base64.Encoder; Last : Stream_Element_Offset; Encoded : Stream_Element_Offset; begin Factory.Lock.Write; -- Generate the random sequence. for I in 0 .. Factory.Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Factory.Random); begin Rand (4 * I) := Stream_Element (Value and 16#0FF#); Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; Factory.Lock.Release_Write; -- Encode the random stream in base64 and save it into the Id string. Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); Id := new String (1 .. Natural (Encoded + 1)); for I in 0 .. Encoded loop Id (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; Log.Info ("Allocated session {0}", Id.all); end Allocate_Session_Id; -- ------------------------------ -- Create a new session -- ------------------------------ procedure Create_Session (Factory : in out Session_Factory; Result : out Session) is Sess : Session; Impl : constant Session_Record_Access := new Session_Record '(Ada.Finalization.Limited_Controlled with Ref_Counter => Util.Concurrent.Counters.ONE, Create_Time => Ada.Calendar.Clock, Max_Inactive => Factory.Max_Inactive, others => <>); begin Impl.Access_Time := Impl.Create_Time; Sess.Impl := Impl; Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id); Factory.Lock.Write; Factory.Sessions.Insert (Impl.Id.all'Access, Sess); Factory.Lock.Release_Write; Result := Sess; end Create_Session; -- ------------------------------ -- Deletes the session. -- ------------------------------ procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session) is begin null; end Delete_Session; -- ------------------------------ -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. -- ------------------------------ procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session) is begin Result := Null_Session; Factory.Lock.Read; declare Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access); begin if Session_Maps.Has_Element (Pos) then Result := Session_Maps.Element (Pos); end if; end; Factory.Lock.Release_Read; if Result.Is_Valid then Result.Impl.Access_Time := Ada.Calendar.Clock; Log.Info ("Found active session {0}", Id); else Log.Info ("Invalid session {0}", Id); end if; end Find_Session; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is begin return Factory.Max_Inactive; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration) is begin Factory.Max_Inactive := Interval; end Set_Max_Inactive_Interval; -- ------------------------------ -- Initialize the session factory. -- ------------------------------ overriding procedure Initialize (Factory : in out Session_Factory) is begin Id_Random.Reset (Factory.Random); end Initialize; end ASF.Sessions.Factory;
Fix compilation on arm
Fix compilation on arm
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
34a1927b2c6952bb911fa894ea2d8157bcca05ac
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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.Requests.Tools; with ASF.Servlets.Faces; with Ada.Directories; 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; 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); Faces : aliased ASF.Servlets.Faces.Faces_Servlet; List : Util.Beans.Basic.Readonly_Bean_Access; List_Bean : Util.Beans.Objects.Object; begin List := Applications.Tests.Create_Form_List; List_Bean := Util.Beans.Objects.To_Object (List); 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.Set_Global ("function", "Test_Load_Facelet"); App.Set_Global ("date", "2011-12-03 03:04:05.23"); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Rep : aliased ASF.Responses.Mockup.Response; Content : Unbounded_String; begin ASF.Requests.Tools.Set_Context (Req => Req, Servlet => Faces'Unchecked_Access, Response => Rep'Unchecked_Access); 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)); Req.Set_Attribute ("list", List_Bean); 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;
----------------------------------------------------------------------- -- 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.Requests.Tools; with ASF.Servlets.Faces; with ASF.Converters.Dates; with Ada.Directories; 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; 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); 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; 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); 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"); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Rep : aliased ASF.Responses.Mockup.Response; Content : Unbounded_String; begin ASF.Requests.Tools.Set_Context (Req => Req, Servlet => Faces'Unchecked_Access, Response => Rep'Unchecked_Access); 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)); Req.Set_Attribute ("list", List_Bean); Req.Set_Attribute ("form", Form_Bean); 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;
Add a form bean for the test Add a date converter for the <f:converter> test
Add a form bean for the test Add a date converter for the <f:converter> test
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
e8a98cdc87f33d07d743ba89b19ac7ff6e28b0d1
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; -- with EL.Functions; limited with Security.Controllers; limited with Security.Contexts; -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package Security.Permissions is -- EL function name exposed by Set_Functions. HAS_PERMISSION_FN : constant String := "hasPermission"; -- URI for the EL functions exposed by the security package (See Set_Functions). AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth"; Invalid_Name : exception; type Security_Context_Access is access all Contexts.Security_Context'Class; type Permission_Index is new Natural; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Abstract_Permission is abstract tagged limited null record; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Role_Type) return Boolean is abstract; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; -- ------------------------------ -- Permission -- ------------------------------ -- Represents a permission for a given role. type Permission (Role : Permission_Type) is new Abstract_Permission with null record; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Abstract_Permission with record URI : String (1 .. Len); end record; -- ------------------------------ -- File Permission -- ------------------------------ type File_Mode is (READ, WRITE); -- Represents a permission to access a given file. type File_Permission (Len : Natural; Mode : File_Mode) is new Abstract_Permission with record Path : String (1 .. Len); end record; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Permission_Manager is new Ada.Finalization.Limited_Controlled with private; type Permission_Manager_Access is access all Permission_Manager'Class; procedure Add_Permission (Manager : in out Permission_Manager; Name : in String; Permission : in Controller_Access); -- 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 Permission_Manager; Name : in String) return Role_Type; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in Permission_Manager; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Returns True if the user has the given role permission. function Has_Permission (Manager : in Permission_Manager; User : in Principal'Class; Permission : in Permission_Type) return Boolean; -- 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 Permission_Manager'Class; Index : in Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Get the role name. function Get_Role_Name (Manager : in Permission_Manager; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Permission_Manager; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Permission_Manager; Name : in String; Result : out Role_Type); -- 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 Permission_Manager; URI : in String; To : in String); -- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b> -- permissions. procedure Grant_File_Permission (Manager : in out Permission_Manager; Path : in String; To : in String); -- Read the policy file procedure Read_Policy (Manager : in out Permission_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Permission_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Permission_Manager); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Permission_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Security.Permissions.Permission_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; -- Register a set of functions in the namespace -- xmlns:fn="http://code.google.com/p/ada-asf/auth" -- Functions: -- hasPermission(NAME) -- Returns True if the permission NAME is granted -- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); private use Util.Strings; type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permission_Index; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- No rule -- No_Rule : constant Access_Rule := (Count => 0, -- Permissions => (others => Permission_Index'First)); -- 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 Permission_Manager; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type Permission_Manager is new Ada.Finalization.Limited_Controlled with record Names : Role_Name_Array; Cache : Rules_Ref_Access; Next_Role : Role_Type := Role_Type'First; Policies : Policy_Vector.Vector; Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; end record; -- EL function to check if the given permission name is granted by the current -- security context. function Has_Permission (Value : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; limited with Security.Controllers; limited with Security.Contexts; -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- package Security.Permissions is -- EL function name exposed by Set_Functions. HAS_PERMISSION_FN : constant String := "hasPermission"; -- URI for the EL functions exposed by the security package (See Set_Functions). AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth"; Invalid_Name : exception; type Security_Context_Access is access all Contexts.Security_Context'Class; type Permission_Index is new Natural; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Abstract_Permission is abstract tagged limited null record; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Role_Type) return Boolean is abstract; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; -- ------------------------------ -- Permission -- ------------------------------ -- Represents a permission for a given role. type Permission (Role : Permission_Type) is new Abstract_Permission with null record; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Abstract_Permission with record URI : String (1 .. Len); end record; -- ------------------------------ -- File Permission -- ------------------------------ type File_Mode is (READ, WRITE); -- Represents a permission to access a given file. type File_Permission (Len : Natural; Mode : File_Mode) is new Abstract_Permission with record Path : String (1 .. Len); end record; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Permission_Manager is new Ada.Finalization.Limited_Controlled with private; type Permission_Manager_Access is access all Permission_Manager'Class; procedure Add_Permission (Manager : in out Permission_Manager; Name : in String; Permission : in Controller_Access); -- 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 Permission_Manager; Name : in String) return Role_Type; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in Permission_Manager; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Returns True if the user has the given role permission. function Has_Permission (Manager : in Permission_Manager; User : in Principal'Class; Permission : in Permission_Type) return Boolean; -- 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 Permission_Manager'Class; Index : in Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Get the role name. function Get_Role_Name (Manager : in Permission_Manager; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Permission_Manager; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Permission_Manager; Name : in String; Result : out Role_Type); -- 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 Permission_Manager; URI : in String; To : in String); -- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b> -- permissions. procedure Grant_File_Permission (Manager : in out Permission_Manager; Path : in String; To : in String); -- Read the policy file procedure Read_Policy (Manager : in out Permission_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Permission_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Permission_Manager); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Permission_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Security.Permissions.Permission_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; -- Register a set of functions in the namespace -- xmlns:fn="http://code.google.com/p/ada-asf/auth" -- Functions: -- hasPermission(NAME) -- Returns True if the permission NAME is granted -- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); private use Util.Strings; type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permission_Index; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- No rule -- No_Rule : constant Access_Rule := (Count => 0, -- Permissions => (others => Permission_Index'First)); -- 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 Permission_Manager; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type Permission_Manager is new Ada.Finalization.Limited_Controlled with record Names : Role_Name_Array; Cache : Rules_Ref_Access; Next_Role : Role_Type := Role_Type'First; Policies : Policy_Vector.Vector; Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; end record; -- EL function to check if the given permission name is granted by the current -- security context. function Has_Permission (Value : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; end Security.Permissions;
Document the permission and principal
Document the permission and principal
Ada
apache-2.0
stcarrez/ada-security
d1b5569e9a7609b62c8086d760d2874ba3f40d09
mat/src/mat-targets.ads
mat/src/mat-targets.ads
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols; Console : MAT.Consoles.Console_Access; end record; type Target_Type_Access is access all Target_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access); private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; end MAT.Targets;
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols; Console : MAT.Consoles.Console_Access; end record; type Target_Type_Access is access all Target_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access); -- 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; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; end MAT.Targets;
Declare the Find_Process function
Declare the Find_Process function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8f67d3255139c2734af6d3afc8f8b32b4254c71e
awa/plugins/awa-tags/src/awa-tags.ads
awa/plugins/awa-tags/src/awa-tags.ads
----------------------------------------------------------------------- -- awa-tags -- Tags management -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Tags</b> module allows to associate general purpose tags to any database entity. -- It provides a JSF component that allows to insert easily a list of tags in a page and -- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt> -- to define the tags and it will use the <tt>awa:tagList</tt> component to display them. -- A tag cloud is also provided by the <tt>awa:tagCloud</tt> component. -- -- == Model == -- The database model is generic and it uses the <tt>Entity_Type</tt> provided by -- [http://ada-ado.googlecode.com ADO] to associate a tag to entities stored in different -- tables. The <tt>Entity_Type</tt> identifies the database table and the stored identifier -- in <tt>for_entity_id</tt> defines the entity in that table. -- -- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png] -- -- @include awa-tags-modules.ads -- @include awa-tags-beans.ads -- @include awa-tags-components.ads -- package AWA.Tags is pragma Pure; end AWA.Tags;
----------------------------------------------------------------------- -- awa-tags -- Tags management -- 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. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Tags</b> module allows to associate general purpose tags to any database entity. -- It provides a JSF component that allows to insert easily a list of tags in a page and -- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt> -- to define the tags and it will use the <tt>awa:tagList</tt> component to display them. -- A tag cloud is also provided by the <tt>awa:tagCloud</tt> component. -- -- == Model == -- The database model is generic and it uses the <tt>Entity_Type</tt> provided by -- [http://ada-ado.googlecode.com ADO] to associate a tag to entities stored in different -- tables. The <tt>Entity_Type</tt> identifies the database table and the stored identifier -- in <tt>for_entity_id</tt> defines the entity in that table. -- -- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png] -- -- @include awa-tags-modules.ads -- @include awa-tags-beans.ads -- @include awa-tags-components.ads -- -- == Queries == -- @include tag-queries.xml package AWA.Tags is pragma Pure; end AWA.Tags;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
1d12f6aa5828a2f71fede1337b794137e5e6e62f
asfunit/asf-tests.ads
asfunit/asf-tests.ads
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Servlet.Tests; with Util.Tests; with Util.XUnit; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Called when the testsuite execution has finished. procedure Finish (Status : in Util.XUnit.Status) renames Servlet.Tests.Finish; -- Get the server function Get_Server return access ASF.Server.Container renames Servlet.Tests.Get_Server; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Get; -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Post; -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) renames Servlet.Tests.Do_Req; -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Contains; -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Matches; -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Redirect; -- Check that the response contains the given header. procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Header; type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2015, 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 ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Servlet.Tests; with Util.Tests; with Util.XUnit; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Called when the testsuite execution has finished. procedure Finish (Status : in Util.XUnit.Status) renames Servlet.Tests.Finish; -- Get the server function Get_Server return access ASF.Server.Container renames Servlet.Tests.Get_Server; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Get; -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request'Class; Response : in out ASF.Responses.Mockup.Response'Class; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Post; -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request'Class; Response : in out ASF.Responses.Mockup.Response'Class) renames Servlet.Tests.Do_Req; -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Contains; -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Matches; -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Redirect; -- Check that the response contains the given header. procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Header; type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
Update Do_Req and Do_Post definitions
Update Do_Req and Do_Post definitions
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c37ef51c4d45a6fc8d1ed6659a0ddacd869e62d7
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; 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;
----------------------------------------------------------------------- -- 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); -- Enable or disable the bbox management by Druss. procedure Do_Enable (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; State : in Boolean; 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 Do_Enable procedure
Declare the Do_Enable procedure
Ada
apache-2.0
stcarrez/bbox-ada-api