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
3f02457162992d0ddf18eba5a5fc55d5d8221351
awa/regtests/awa-users-tests.adb
awa/regtests/awa-users-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register", "1"); Request.Set_Parameter ("register-button", "1"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "[email protected]"; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/reset-password.html", "reset-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Post the reset password Request.Set_Parameter ("password", "asd"); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Test_Reset_Password_User; end AWA.Users.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register", "1"); Request.Set_Parameter ("register-button", "1"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/auth/validate.html", "validate-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "[email protected]"; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", "asd"); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Test_Reset_Password_User; end AWA.Users.Tests;
Update the unit test according to the lost password recovery process
Update the unit test according to the lost password recovery process
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4c57b8b3615bac4e980d5a8156d5d405788527f1
src/ado-drivers.ads
src/ado-drivers.ads
----------------------------------------------------------------------- -- 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.Properties; -- = Database Drivers == -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. The driver -- is either statically linked to the application and can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by <b>libada_ado_</b>. For example, for a <tt>mysql</tt> driver, the shared -- library name is <tt>libada_ado_mysql.so</tt>. -- -- == Initialization == -- The <b>ADO</b> runtime must be initialized by calling one of the <b>Initialize</b> operation. -- A property file contains the configuration for the database drivers and the database -- connection properties. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- Once initialized, a configuration property can be retrieved by using the <tt>Get_Config</tt> -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; private -- Initialize the drivers which are available. procedure Initialize; 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.Properties; -- = Database Drivers == -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. The driver -- is either statically linked to the application and can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by <b>libada_ado_</b>. For example, for a <tt>mysql</tt> driver, the shared -- library name is <tt>libada_ado_mysql.so</tt>. -- -- == Initialization == -- The <b>ADO</b> runtime must be initialized by calling one of the <b>Initialize</b> operation. -- A property file contains the configuration for the database drivers and the database -- connection properties. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- Once initialized, a configuration property can be retrieved by using the <tt>Get_Config</tt> -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database. Database_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; private -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
Rename the DB_Error exception into Database_Error
Rename the DB_Error exception into Database_Error
Ada
apache-2.0
stcarrez/ada-ado
a6b04740f29c58acd9f739ec2faaa413a55cc8f1
src/asf-locales.ads
src/asf-locales.ads
----------------------------------------------------------------------- -- asf-locales -- Locale support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Maps; with Util.Properties.Bundles; with Util.Locales; with ASF.Beans; with ASF.Requests; -- The <b>ASF.Locales</b> package manages everything related to the locales. -- It allows to register bundles that contains localized messages and be able -- to use them in the facelet views. package ASF.Locales is -- To keep the implementation simple, the maximum list of supported locales by the -- application is limited to 32. Most applications support 1 or 2 languages. MAX_SUPPORTED_LOCALES : constant Positive := 32; type Bundle is new Util.Properties.Bundles.Manager and Util.Beans.Basic.Readonly_Bean with null record; type Bundle_Access is access all Bundle; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Bundle; Name : in String) return Util.Beans.Objects.Object; type Factory is limited private; -- Initialize the locale support by using the configuration properties. -- Properties matching the pattern: <b>bundles</b>.<i>var-name</i>=<i>bundle-name</i> -- are used to register bindings linking a facelet variable <i>var-name</i> -- to the resource bundle <i>bundle-name</i>. procedure Initialize (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Config : in Util.Properties.Manager'Class); -- Register a bundle and bind it to a facelet variable. procedure Register (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Name : in String; Bundle : in String); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (Fac : in out Factory; Name : in String; Locale : in String; Result : out Bundle); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Fac : in Factory; Req : in ASF.Requests.Request'Class) return Util.Locales.Locale; -- Get the list of supported locales for this application. function Get_Supported_Locales (From : in Factory) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (Into : in out Factory; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (From : in Factory) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (Into : in out Factory; Locale : in Util.Locales.Locale); private type Factory is limited record Factory : aliased Util.Properties.Bundles.Loader; Bundles : Util.Strings.Maps.Map; -- The default locale used by the application. Default_Locale : Util.Locales.Locale := Util.Locales.ENGLISH; -- Number of supported locales. Nb_Locales : Natural := 0; -- The list of supported locales. Locales : Util.Locales.Locale_Array (1 .. MAX_SUPPORTED_LOCALES); end record; type Factory_Access is access all Factory; end ASF.Locales;
----------------------------------------------------------------------- -- asf-locales -- Locale support -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Maps; with Util.Properties.Bundles; with Util.Locales; with ASF.Beans; with ASF.Requests; -- The <b>ASF.Locales</b> package manages everything related to the locales. -- It allows to register bundles that contains localized messages and be able -- to use them in the facelet views. package ASF.Locales is -- To keep the implementation simple, the maximum list of supported locales by the -- application is limited to 32. Most applications support 1 or 2 languages. MAX_SUPPORTED_LOCALES : constant Positive := 32; type Bundle is new Util.Properties.Bundles.Manager and Util.Beans.Basic.Readonly_Bean with null record; type Bundle_Access is access all Bundle; type Factory is limited private; -- Initialize the locale support by using the configuration properties. -- Properties matching the pattern: <b>bundles</b>.<i>var-name</i>=<i>bundle-name</i> -- are used to register bindings linking a facelet variable <i>var-name</i> -- to the resource bundle <i>bundle-name</i>. procedure Initialize (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Config : in Util.Properties.Manager'Class); -- Register a bundle and bind it to a facelet variable. procedure Register (Fac : in out Factory; Beans : in out ASF.Beans.Bean_Factory; Name : in String; Bundle : in String); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (Fac : in out Factory; Name : in String; Locale : in String; Result : out Bundle); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Fac : in Factory; Req : in ASF.Requests.Request'Class) return Util.Locales.Locale; -- Get the list of supported locales for this application. function Get_Supported_Locales (From : in Factory) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (Into : in out Factory; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (From : in Factory) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (Into : in out Factory; Locale : in Util.Locales.Locale); private type Factory is limited record Factory : aliased Util.Properties.Bundles.Loader; Bundles : Util.Strings.Maps.Map; -- The default locale used by the application. Default_Locale : Util.Locales.Locale := Util.Locales.ENGLISH; -- Number of supported locales. Nb_Locales : Natural := 0; -- The list of supported locales. Locales : Util.Locales.Locale_Array (1 .. MAX_SUPPORTED_LOCALES); end record; type Factory_Access is access all Factory; end ASF.Locales;
Remove the Get_Value function because it is already provided by the property manager
Remove the Get_Value function because it is already provided by the property manager
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c390110021871d1db88a5707ed0327fde5048076
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Filters.Html; with Wiki.Filters.TOC; 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 = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; 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; -- ------------------------------ -- 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; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Links.Link_Renderer_Access; Engine : Wiki.Parsers.Parser; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_Wide_Wide_String (Value), Doc); Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Render (Doc); end if; Writer.End_Element ("div"); 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 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 Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : 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 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Filters.Html; with Wiki.Filters.TOC; 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 = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; 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, 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 Wiki.Plugins.Plugin_Factory'Class) then return null; else return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access; end if; end Get_Plugin_Factory; -- ------------------------------ -- 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; Html : aliased Html_Writer_Type; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); 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); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_Wide_Wide_String (Value), Doc); Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Render (Doc); end if; Writer.End_Element ("div"); 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 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 Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : 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 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;
Implement Get_Plugin_Factory function and use it to configure the Wiki parser
Implement Get_Plugin_Factory function and use it to configure the Wiki parser
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6e7ba9c1db5ad61da7009d1374db018cd0c8984a
mat/src/mat-readers.ads
mat/src/mat-readers.ads
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with System; with Util.Streams.Buffered; with MAT.Types; with MAT.Events; with MAT.Events.Targets; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out Message) is abstract; ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with private; type Manager is access all Manager_Base'Class; -- Initialize the manager instance. overriding procedure Initialize (Manager : in out Manager_Base); -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); -- Read a message from the stream. procedure Read_Message (Client : in out Manager_Base; Msg : in out Message) is abstract; -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Manager_Base; Msg : in out Message); -- Get the target events. function Get_Target_Events (Client : in Manager_Base) return MAT.Events.Targets.Target_Events_Access; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_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 (List : in out Reader_List_Type; Reader : in out Manager_Base'Class) is abstract; private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Buffer : Util.Streams.Buffered.Buffer_Access; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; end record; -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message); -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with System; with Util.Streams.Buffered; with MAT.Types; with MAT.Events; with MAT.Events.Targets; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message_Type is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; subtype Message is Message_Type; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Extract (For_Servant : in out Reader_Base; Event : in out MAT.Events.Targets.Target_Event; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out Message) is null; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out Message) is abstract; ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with private; type Manager is access all Manager_Base'Class; -- Initialize the manager instance. overriding procedure Initialize (Manager : in out Manager_Base); -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); -- Read a message from the stream. procedure Read_Message (Client : in out Manager_Base; Msg : in out Message) is abstract; -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Manager_Base; Msg : in out Message); -- Get the target events. function Get_Target_Events (Client : in Manager_Base) return MAT.Events.Targets.Target_Events_Access; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_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 (List : in out Reader_List_Type; Reader : in out Manager_Base'Class) is abstract; private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Buffer : Util.Streams.Buffered.Buffer_Access; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is abstract new Ada.Finalization.Limited_Controlled with record Readers : Reader_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; end record; -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message); -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
Rename the Message type into Message_Type
Rename the Message type into Message_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ffc141eb44d6b0b9e77ec3e44e56aab7fd6d8316
src/mysql/ado-schemas-mysql.adb
src/mysql/ado-schemas-mysql.adb
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Statements; with ADO.Statements.Create; with ADO.SQL; with Ada.Strings.Fixed; package body ADO.Schemas.Mysql is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int(11)" then return T_INTEGER; elsif Value = "bigint(20)" then return T_LONG_INTEGER; elsif Value = "tinyint(4)" then return T_TINYINT; elsif Value = "smallint(6)" then return T_SMALLINT; elsif Value = "longblob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "decimal" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show full columns from ")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; Query : constant ADO.SQL.Query_Access := Stmt.Get_Query; begin ADO.SQL.Append_Name (Target => Query.SQL, Name => Name); Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (0); if not Stmt.Is_Null (2) then Col.Collation := Stmt.Get_Unbounded_String (2); end if; if not Stmt.Is_Null (5) then Col.Default := Stmt.Get_Unbounded_String (5); end if; if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (1); Col.Col_Type := String_To_Type (To_String (Value)); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "YES"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show tables")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop Table := new ADO.Schemas.Table; Table.Name := Stmt.Get_Unbounded_String (0); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Mysql;
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Statements; with ADO.Statements.Create; with ADO.SQL; with Ada.Strings.Fixed; package body ADO.Schemas.Mysql is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int(11)" then return T_INTEGER; elsif Value = "bigint(20)" then return T_LONG_INTEGER; elsif Value = "tinyint(4)" then return T_TINYINT; elsif Value = "smallint(6)" then return T_SMALLINT; elsif Value = "longblob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "decimal" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show full columns from ")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; Query : constant ADO.SQL.Query_Access := Stmt.Get_Query; begin ADO.SQL.Append_Name (Target => Query.SQL, Name => Name); Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (0); if not Stmt.Is_Null (2) then Col.Collation := Stmt.Get_Unbounded_String (2); end if; if not Stmt.Is_Null (5) then Col.Default := Stmt.Get_Unbounded_String (5); end if; if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (1); Col.Col_Type := String_To_Type (To_String (Value)); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "YES"; Value := Stmt.Get_Unbounded_String (4); Col.Is_Primary := Value = "PRI"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("show tables")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop Table := new ADO.Schemas.Table; Table.Name := Stmt.Get_Unbounded_String (0); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Mysql;
Set the Is_Primary column attribute if the column is a primary key
Set the Is_Primary column attribute if the column is a primary key
Ada
apache-2.0
stcarrez/ada-ado
dff287f7fc6529801b322a620d00beb77aed2257
src/wiki-filters-collectors.ads
src/wiki-filters-collectors.ads
----------------------------------------------------------------------- -- wiki-filters-collectors -- Wiki word and link collectors -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Ordered_Maps; -- === Collector Filters === -- The <tt>Wiki.Filters.Collectors</tt> package defines two filters that can be used to -- collect words or links contained in a Wiki document. The collector filters are inserted -- in the filter chain and they collect the data as the Wiki text is parsed. After the -- parsing, the collector filters have collected either the words or the links and they -- can be queried by using the <tt>Find</tt> or <tt>Iterate</tt> operations. package Wiki.Filters.Collectors is pragma Preelaborate; package WString_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Natural, "<" => "<", "=" => "="); subtype Map is WString_Maps.Map; subtype Cursor is WString_Maps.Cursor; -- ------------------------------ -- General purpose collector type -- ------------------------------ type Collector_Type is new Filter_Type with private; type Collector_Type_Access is access all Collector_Type'Class; function Find (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Cursor; function Contains (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Boolean; procedure Iterate (Map : in Collector_Type; Process : not null access procedure (Pos : in Cursor)); -- ------------------------------ -- Word Collector type -- ------------------------------ type Word_Collector_Type is new Collector_Type with private; type Word_Collector_Type_Access is access all Word_Collector_Type'Class; -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a link. procedure Add_Link (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- ------------------------------ -- Link Collector type -- ------------------------------ type Link_Collector_Type is new Collector_Type with private; type Link_Collector_Type_Access is access all Link_Collector_Type'Class; -- Add a link. overriding procedure Add_Link (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Push a HTML node with the given tag to the document. overriding procedure Push_Node (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); -- ------------------------------ -- Image Collector type -- ------------------------------ type Image_Collector_Type is new Collector_Type with private; type Image_Collector_Type_Access is access all Image_Collector_Type'Class; -- Add an image. overriding procedure Add_Image (Filter : in out Image_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); private type Collector_Type is new Filter_Type with record Items : WString_Maps.Map; end record; type Word_Collector_Type is new Collector_Type with null record; procedure Collect_Words (Filter : in out Word_Collector_Type; Content : in Wiki.Strings.WString); type Link_Collector_Type is new Collector_Type with null record; procedure Collect_Link (Filter : in out Link_Collector_Type; Attributes : in Wiki.Attributes.Attribute_List; Name : in String); type Image_Collector_Type is new Collector_Type with null record; end Wiki.Filters.Collectors;
----------------------------------------------------------------------- -- wiki-filters-collectors -- Wiki word and link collectors -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Ordered_Maps; -- === Collector Filters === -- The <tt>Wiki.Filters.Collectors</tt> package defines three filters that can be used to -- collect words, links or images contained in a Wiki document. The collector filters are -- inserted in the filter chain and they collect the data as the Wiki text is parsed. -- After the parsing, the collector filters have collected either the words or the links -- and they can be queried by using the <tt>Find</tt> or <tt>Iterate</tt> operations. -- -- The filter is inserted in the filter chain before parsing the Wiki document. -- -- Words : aliased Wiki.Filters.Collectors.Word_Collector_Type; -- ... -- Engine.Add_Filter (Words'Unchecked_Access); -- -- Once the document is parsed, the collector filters contains the data that was collected. -- The <tt>Iterate</tt> procedure can be used to have a procedure called for each value -- collected by the filter. -- -- Words.Iterate (Print'Access); -- package Wiki.Filters.Collectors is pragma Preelaborate; package WString_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Natural, "<" => "<", "=" => "="); subtype Map is WString_Maps.Map; subtype Cursor is WString_Maps.Cursor; -- ------------------------------ -- General purpose collector type -- ------------------------------ type Collector_Type is new Filter_Type with private; type Collector_Type_Access is access all Collector_Type'Class; function Find (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Cursor; function Contains (Map : in Collector_Type; Item : in Wiki.Strings.WString) return Boolean; procedure Iterate (Map : in Collector_Type; Process : not null access procedure (Pos : in Cursor)); -- ------------------------------ -- Word Collector type -- ------------------------------ type Word_Collector_Type is new Collector_Type with private; type Word_Collector_Type_Access is access all Word_Collector_Type'Class; -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a link. procedure Add_Link (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Filter : in out Word_Collector_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- ------------------------------ -- Link Collector type -- ------------------------------ type Link_Collector_Type is new Collector_Type with private; type Link_Collector_Type_Access is access all Link_Collector_Type'Class; -- Add a link. overriding procedure Add_Link (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Push a HTML node with the given tag to the document. overriding procedure Push_Node (Filter : in out Link_Collector_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); -- ------------------------------ -- Image Collector type -- ------------------------------ type Image_Collector_Type is new Collector_Type with private; type Image_Collector_Type_Access is access all Image_Collector_Type'Class; -- Add an image. overriding procedure Add_Image (Filter : in out Image_Collector_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); private type Collector_Type is new Filter_Type with record Items : WString_Maps.Map; end record; type Word_Collector_Type is new Collector_Type with null record; procedure Collect_Words (Filter : in out Word_Collector_Type; Content : in Wiki.Strings.WString); type Link_Collector_Type is new Collector_Type with null record; procedure Collect_Link (Filter : in out Link_Collector_Type; Attributes : in Wiki.Attributes.Attribute_List; Name : in String); type Image_Collector_Type is new Collector_Type with null record; end Wiki.Filters.Collectors;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f2d11128bb48c746ecf664a888d462c3b73a6127
src/http/curl/util-http-clients-curl.ads
src/http/curl/util-http-clients-curl.ads
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- with System; with Interfaces.C; with Interfaces.C.Strings; with Ada.Strings.Unbounded; with Util.Http.Mockups; package Util.Http.Clients.Curl is -- Register the CURL Http manager. procedure Register; private package C renames Interfaces.C; package Strings renames Interfaces.C.Strings; use type C.size_t; use type C.int; -- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due -- to Eclipse capitalization. subtype Int is C.int; subtype Chars_Ptr is Strings.chars_ptr; subtype Size_T is C.size_t; subtype CURL is System.Address; type CURL_Code is new Interfaces.C.int; CURLE_OK : constant CURL_Code := 0; type CURL_Info is new Int; type Curl_Option is new Int; type CURL_Slist; type CURL_Slist_Access is access CURL_Slist; type CURL_Slist is record Data : Chars_Ptr; Next : CURL_Slist_Access; end record; -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. procedure Check_Code (Code : in CURL_Code; Message : in String); type Curl_Http_Manager is new Http_Manager with null record; type Curl_Http_Manager_Access is access all Http_Manager'Class; -- Create a new HTTP request associated with the current request manager. procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class); overriding procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); overriding procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record Data : CURL := System.Null_Address; URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Curl_Headers : CURL_Slist_Access := null; end record; type Curl_Http_Request_Access is access all Curl_Http_Request'Class; -- Prepare to setup the headers in the request. procedure Set_Headers (Request : in out Curl_Http_Request); overriding procedure Finalize (Request : in out Curl_Http_Request); type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record C : CURL; Content : Ada.Strings.Unbounded.Unbounded_String; Status : Natural; Parsing_Body : Boolean := False; end record; type Curl_Http_Response_Access is access all Curl_Http_Response'Class; -- Get the response body as a string. overriding function Get_Body (Reply : in Curl_Http_Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Curl_Http_Response) return Natural; -- Add a string to a CURL slist. function Curl_Slist_Append (List : in CURL_Slist_Access; Value : in Chars_Ptr) return CURL_Slist_Access; pragma Import (C, Curl_Slist_Append, "curl_slist_append"); -- Free an entrire CURL slist. procedure Curl_Slist_Free_All (List : in CURL_Slist_Access); pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all"); -- Start a libcurl easy session. function Curl_Easy_Init return CURL; pragma Import (C, Curl_Easy_Init, "curl_easy_init"); -- End a libcurl easy session. procedure Curl_Easy_Cleanup (Handle : in CURL); pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup"); -- Perform a file transfer. function Curl_Easy_Perform (Handle : in CURL) return CURL_Code; pragma Import (C, Curl_Easy_Perform, "curl_easy_perform"); -- Return the error message which correspond to the given CURL error code. function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr; pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_String (Handle : in CURL; Option : in Curl_Option; Value : in Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Slist (Handle : in CURL; Option : in Curl_Option; Value : in CURL_Slist_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Long (Handle : in CURL; Option : in Curl_Option; Value : in Interfaces.C.long) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt"); -- Get information from a CURL handle for an option returning a String. function Curl_Easy_Getinfo_String (Handle : in CURL; Option : in CURL_Info; Value : access Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo"); -- Get information from a CURL handle for an option returning a Long. function Curl_Easy_Getinfo_Long (Handle : in CURL; Option : in CURL_Info; Value : access C.long) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo"); function Curl_Easy_Setopt_Write_Callback (Handle : in CURL; Option : in Curl_Option; Func : access function (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Ptr : in Curl_Http_Response_Access) return Size_T) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Data (Handle : in CURL; Option : in Curl_Option; Value : in Curl_Http_Response_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt"); function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T; end Util.Http.Clients.Curl;
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- with System; with Interfaces.C; with Interfaces.C.Strings; with Ada.Strings.Unbounded; with Util.Http.Mockups; package Util.Http.Clients.Curl is -- Register the CURL Http manager. procedure Register; private package C renames Interfaces.C; package Strings renames Interfaces.C.Strings; use type C.size_t; use type C.int; -- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due -- to Eclipse capitalization. subtype Int is C.int; subtype Chars_Ptr is Strings.chars_ptr; subtype Size_T is C.size_t; subtype CURL is System.Address; type CURL_Code is new Interfaces.C.int; CURLE_OK : constant CURL_Code := 0; type CURL_Info is new Int; type Curl_Option is new Int; type CURL_Slist; type CURL_Slist_Access is access CURL_Slist; type CURL_Slist is record Data : Chars_Ptr; Next : CURL_Slist_Access; end record; -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. procedure Check_Code (Code : in CURL_Code; Message : in String); type Curl_Http_Manager is new Http_Manager with null record; type Curl_Http_Manager_Access is access all Http_Manager'Class; -- Create a new HTTP request associated with the current request manager. procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class); overriding procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); overriding procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); -- Set the timeout for the connection. overriding procedure Set_Timeout (Manager : in Curl_Http_Manager; Http : in Client'Class; Timeout : in Duration); type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record Data : CURL := System.Null_Address; URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Curl_Headers : CURL_Slist_Access := null; end record; type Curl_Http_Request_Access is access all Curl_Http_Request'Class; -- Prepare to setup the headers in the request. procedure Set_Headers (Request : in out Curl_Http_Request); overriding procedure Finalize (Request : in out Curl_Http_Request); type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record C : CURL; Content : Ada.Strings.Unbounded.Unbounded_String; Status : Natural; Parsing_Body : Boolean := False; end record; type Curl_Http_Response_Access is access all Curl_Http_Response'Class; -- Get the response body as a string. overriding function Get_Body (Reply : in Curl_Http_Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Curl_Http_Response) return Natural; -- Add a string to a CURL slist. function Curl_Slist_Append (List : in CURL_Slist_Access; Value : in Chars_Ptr) return CURL_Slist_Access; pragma Import (C, Curl_Slist_Append, "curl_slist_append"); -- Free an entrire CURL slist. procedure Curl_Slist_Free_All (List : in CURL_Slist_Access); pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all"); -- Start a libcurl easy session. function Curl_Easy_Init return CURL; pragma Import (C, Curl_Easy_Init, "curl_easy_init"); -- End a libcurl easy session. procedure Curl_Easy_Cleanup (Handle : in CURL); pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup"); -- Perform a file transfer. function Curl_Easy_Perform (Handle : in CURL) return CURL_Code; pragma Import (C, Curl_Easy_Perform, "curl_easy_perform"); -- Return the error message which correspond to the given CURL error code. function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr; pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_String (Handle : in CURL; Option : in Curl_Option; Value : in Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Slist (Handle : in CURL; Option : in Curl_Option; Value : in CURL_Slist_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Long (Handle : in CURL; Option : in Curl_Option; Value : in Interfaces.C.long) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt"); -- Get information from a CURL handle for an option returning a String. function Curl_Easy_Getinfo_String (Handle : in CURL; Option : in CURL_Info; Value : access Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo"); -- Get information from a CURL handle for an option returning a Long. function Curl_Easy_Getinfo_Long (Handle : in CURL; Option : in CURL_Info; Value : access C.long) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo"); function Curl_Easy_Setopt_Write_Callback (Handle : in CURL; Option : in Curl_Option; Func : access function (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Ptr : in Curl_Http_Response_Access) return Size_T) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Data (Handle : in CURL; Option : in Curl_Option; Value : in Curl_Http_Response_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt"); function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T; end Util.Http.Clients.Curl;
Declare the Set_Timeout procedure
Declare the Set_Timeout procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
35208ed156fcb24f3e3a0fed13c2f6da66e3e1a6
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Used_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; end Memory_Allocator; end MAT.Memory.Targets;
Implement the protected operation Size_Information
Implement the protected operation Size_Information
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
47ac340bf4b073c618cdc0d3575d0186ebe6f3de
awa/samples/src/atlas-reviews-modules.ads
awa/samples/src/atlas-reviews-modules.ads
----------------------------------------------------------------------- -- atlas-reviews-modules -- Module reviews -- 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 ASF.Applications; with AWA.Modules; with Atlas.Reviews.Models; with Security.Permissions; package Atlas.Reviews.Modules is -- The name under which the module is registered. NAME : constant String := "reviews"; package ACL_Create_Reviews is new Security.Permissions.Definition ("review-create"); package ACL_Delete_Reviews is new Security.Permissions.Definition ("review-delete"); package ACL_Update_Reviews is new Security.Permissions.Definition ("review-update"); -- ------------------------------ -- Module reviews -- ------------------------------ type Review_Module is new AWA.Modules.Module with private; type Review_Module_Access is access all Review_Module'Class; -- Initialize the reviews module. overriding procedure Initialize (Plugin : in out Review_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the reviews module. function Get_Review_Module return Review_Module_Access; -- save procedure save (Model : in Review_Module; Entity : in out Atlas.Reviews.Models.Review_Ref'Class); -- delete procedure delete (Model : in Review_Module; Entity : in out Atlas.Reviews.Models.Review_Ref'Class); private type Review_Module is new AWA.Modules.Module with null record; end Atlas.Reviews.Modules;
----------------------------------------------------------------------- -- atlas-reviews-modules -- Module reviews -- 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 ASF.Applications; with AWA.Modules; with Atlas.Reviews.Models; with Security.Permissions; package Atlas.Reviews.Modules is -- The name under which the module is registered. NAME : constant String := "reviews"; package ACL_Create_Reviews is new Security.Permissions.Definition ("review-create"); package ACL_Delete_Reviews is new Security.Permissions.Definition ("review-delete"); package ACL_Update_Reviews is new Security.Permissions.Definition ("review-update"); -- ------------------------------ -- Module reviews -- ------------------------------ type Review_Module is new AWA.Modules.Module with private; type Review_Module_Access is access all Review_Module'Class; -- Initialize the reviews module. overriding procedure Initialize (Plugin : in out Review_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the reviews module. function Get_Review_Module return Review_Module_Access; -- Save the review. procedure Save (Model : in Review_Module; Entity : in out Atlas.Reviews.Models.Review_Ref'Class); -- Delete the review. procedure Delete (Model : in Review_Module; Entity : in out Atlas.Reviews.Models.Review_Ref'Class); private type Review_Module is new AWA.Modules.Module with null record; end Atlas.Reviews.Modules;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0ac29f20e5b59be0dfdf0e4edf52c7814c32af92
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 Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); 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 : constant 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 : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); 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 : constant Object_Pointer := To_Pointer (Buffer.Current + Storage_Offset (1)); Low : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); 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 : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); 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 : constant 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 => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); 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; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; 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 Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); 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 : constant 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 : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); 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 : constant Object_Pointer := To_Pointer (Buffer.Current + Storage_Offset (1)); Low : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); 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 : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); 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 : constant 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 => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); 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; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
Implement the Get_String operation
Implement the Get_String operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c2c1b3b99aac2b671b4690df204846e4b1b9104b
awa/src/awa-services-contexts.adb
awa/src/awa-services-contexts.adb
----------------------------------------------------------------------- -- awa-services -- Services -- 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.Task_Attributes; with ADO.Databases; package body AWA.Services.Contexts is use type ADO.Databases.Connection_Status; use type AWA.Users.Principals.Principal_Access; package Task_Context is new Ada.Task_Attributes (Service_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_Application (Ctx : in Service_Context) return AWA.Applications.Application_Access is begin return Ctx.Application; end Get_Application; -- ------------------------------ -- Get the current database connection for reading. -- ------------------------------ function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is begin if Ctx.Slave.Get_Status /= ADO.Databases.OPEN then Ctx.Slave := Ctx.Application.Get_Session; end if; return Ctx.Slave; end Get_Session; -- ------------------------------ -- Get the current database connection for reading and writing. -- ------------------------------ function Get_Master_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Master_Session is begin if Ctx.Master.Get_Status /= ADO.Databases.OPEN then Ctx.Master := Ctx.Application.Get_Master_Session; -- Ctx.Slave := Ctx.Master; end if; return Ctx.Master; end Get_Master_Session; -- ------------------------------ -- Get the current user invoking the service operation. -- Returns a null user if there is none. -- ------------------------------ function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_User; else return Ctx.Principal.Get_User; end if; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is begin if Ctx.Principal = null then return ADO.NO_IDENTIFIER; else return Ctx.Principal.Get_User_Identifier; end if; end Get_User_Identifier; -- ------------------------------ -- Get the current user session from the user invoking the service operation. -- Returns a null session if there is none. -- ------------------------------ function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_Session; else return Ctx.Principal.Get_Session; end if; end Get_User_Session; -- ------------------------------ -- Starts a transaction. -- ------------------------------ procedure Start (Ctx : in out Service_Context) is begin if Ctx.Transaction = 0 and then Ctx.Master.Get_Status /= ADO.Databases.OPEN then Ctx.Master.Begin_Transaction; Ctx.Active_Transaction := True; end if; Ctx.Transaction := Ctx.Transaction + 1; end Start; -- ------------------------------ -- Commits the current transaction. The database transaction is really committed by the -- last <b>Commit</b> called. -- ------------------------------ procedure Commit (Ctx : in out Service_Context) is begin Ctx.Transaction := Ctx.Transaction - 1; if Ctx.Transaction = 0 and then Ctx.Active_Transaction then Ctx.Master.Commit; Ctx.Active_Transaction := False; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. The database transaction is rollback at the first -- call to <b>Rollback</b>. -- ------------------------------ procedure Rollback (Ctx : in out Service_Context) is begin null; end Rollback; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Ctx : in out Service_Context; Application : in AWA.Applications.Application_Access; Principal : in AWA.Users.Principals.Principal_Access) is begin Ctx.Application := Application; Ctx.Principal := Principal; end Set_Context; -- ------------------------------ -- Initializes the service context. -- ------------------------------ overriding procedure Initialize (Ctx : in out Service_Context) is use type AWA.Applications.Application_Access; begin Ctx.Previous := Task_Context.Value; Task_Context.Set_Value (Ctx'Unchecked_Access); if Ctx.Previous /= null and then Ctx.Application = null then Ctx.Application := Ctx.Previous.Application; end if; end Initialize; -- ------------------------------ -- Finalize the service context, rollback non-committed transaction, releases any object. -- ------------------------------ overriding procedure Finalize (Ctx : in out Service_Context) is begin -- When the service context is released, we must not have any active transaction. -- This means we are leaving the service in an abnormal way such as when an -- exception is raised. If this is the case, rollback the transaction. if Ctx.Active_Transaction then Ctx.Master.Rollback; end if; Task_Context.Set_Value (Ctx.Previous); end Finalize; -- ------------------------------ -- Get the current service context. -- Returns null if the current thread is not associated with any service context. -- ------------------------------ function Current return Service_Context_Access is begin return Task_Context.Value; end Current; end AWA.Services.Contexts;
----------------------------------------------------------------------- -- awa-services -- Services -- 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.Task_Attributes; with ADO.Databases; package body AWA.Services.Contexts is use type ADO.Databases.Connection_Status; use type AWA.Users.Principals.Principal_Access; package Task_Context is new Ada.Task_Attributes (Service_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_Application (Ctx : in Service_Context) return AWA.Applications.Application_Access is begin return Ctx.Application; end Get_Application; -- ------------------------------ -- Get the current database connection for reading. -- ------------------------------ function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is begin if Ctx.Slave.Get_Status /= ADO.Databases.OPEN then Ctx.Slave := Ctx.Application.Get_Session; end if; return Ctx.Slave; end Get_Session; -- ------------------------------ -- Get the current database connection for reading and writing. -- ------------------------------ function Get_Master_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Master_Session is begin if Ctx.Master.Get_Status /= ADO.Databases.OPEN then Ctx.Master := Ctx.Application.Get_Master_Session; -- Ctx.Slave := Ctx.Master; end if; return Ctx.Master; end Get_Master_Session; -- ------------------------------ -- Get the current user invoking the service operation. -- Returns a null user if there is none. -- ------------------------------ function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_User; else return Ctx.Principal.Get_User; end if; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is begin if Ctx.Principal = null then return ADO.NO_IDENTIFIER; else return Ctx.Principal.Get_User_Identifier; end if; end Get_User_Identifier; -- ------------------------------ -- Get the current user session from the user invoking the service operation. -- Returns a null session if there is none. -- ------------------------------ function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is begin if Ctx.Principal = null then return AWA.Users.Models.Null_Session; else return Ctx.Principal.Get_Session; end if; end Get_User_Session; -- ------------------------------ -- Starts a transaction. -- ------------------------------ procedure Start (Ctx : in out Service_Context) is begin if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then Ctx.Master.Begin_Transaction; Ctx.Active_Transaction := True; end if; Ctx.Transaction := Ctx.Transaction + 1; end Start; -- ------------------------------ -- Commits the current transaction. The database transaction is really committed by the -- last <b>Commit</b> called. -- ------------------------------ procedure Commit (Ctx : in out Service_Context) is begin Ctx.Transaction := Ctx.Transaction - 1; if Ctx.Transaction = 0 and then Ctx.Active_Transaction then Ctx.Master.Commit; Ctx.Active_Transaction := False; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. The database transaction is rollback at the first -- call to <b>Rollback</b>. -- ------------------------------ procedure Rollback (Ctx : in out Service_Context) is begin null; end Rollback; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Ctx : in out Service_Context; Application : in AWA.Applications.Application_Access; Principal : in AWA.Users.Principals.Principal_Access) is begin Ctx.Application := Application; Ctx.Principal := Principal; end Set_Context; -- ------------------------------ -- Initializes the service context. -- ------------------------------ overriding procedure Initialize (Ctx : in out Service_Context) is use type AWA.Applications.Application_Access; begin Ctx.Previous := Task_Context.Value; Task_Context.Set_Value (Ctx'Unchecked_Access); if Ctx.Previous /= null and then Ctx.Application = null then Ctx.Application := Ctx.Previous.Application; end if; end Initialize; -- ------------------------------ -- Finalize the service context, rollback non-committed transaction, releases any object. -- ------------------------------ overriding procedure Finalize (Ctx : in out Service_Context) is begin -- When the service context is released, we must not have any active transaction. -- This means we are leaving the service in an abnormal way such as when an -- exception is raised. If this is the case, rollback the transaction. if Ctx.Active_Transaction then Ctx.Master.Rollback; end if; Task_Context.Set_Value (Ctx.Previous); end Finalize; -- ------------------------------ -- Get the current service context. -- Returns null if the current thread is not associated with any service context. -- ------------------------------ function Current return Service_Context_Access is begin return Task_Context.Value; end Current; end AWA.Services.Contexts;
Fix start transaction when several start/commit sequences are made
Fix start transaction when several start/commit sequences are made
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d86ec654532aa06efe38c2a3a5b4222a42b913c8
src/glfw/glfw-input-joysticks.ads
src/glfw/glfw-input-joysticks.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2013 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Glfw.Enums; package Glfw.Input.Joysticks is pragma Preelaborate; use type Interfaces.C.C_float; type Joystick_Index is range 1 .. 16; -- GLFW supports up to 16 joysticks; they are indexed from 1 to 16 type Joystick is tagged private; -- A Joystick object will link to the first joystick by default type Axis_Position is new Interfaces.C.C_float range -1.0 .. 1.0; type Axis_Positions is array (Positive range <>) of aliased Axis_Position; type Joystick_Button_State is new Button_State; type Joystick_Button_States is array (Positive range <>) of aliased Joystick_Button_State; type Joystick_Gamepad_State is record Buttons : Joystick_Button_States (1 .. 15); Axes : Axis_Positions (1 .. 6); end record with Convention => C; type Joystick_Hat_State is (Centered, Up, Right, Right_Up, Down, Right_Down, Left, Left_Up, Left_Down); type Joystick_Hat_States is array (Positive range <>) of aliased Joystick_Hat_State; type Connect_State is (Connected, Disconnected); function Index (Source : Joystick) return Joystick_Index; procedure Set_Index (Target : in out Joystick; Value : Joystick_Index); function Present (Source : Joystick) return Boolean; function Is_Gamepad (Source : Joystick) return Boolean; function Gamepad_Name (Source : Joystick) return String; function Gamepad_State (Source : Joystick) return Joystick_Gamepad_State; function Joystick_Name (Source : Joystick) return String; function Joystick_GUID (Source : Joystick) return String; procedure Update_Gamepad_Mappings (Mappings : String); function Positions (Source : Joystick) return Axis_Positions; function Button_States (Source : Joystick) return Joystick_Button_States; function Hat_States (Source : Joystick) return Joystick_Hat_States; type Joystick_Callback is access procedure (Source : Joystick; State : Connect_State); procedure Set_Callback (Callback : Joystick_Callback); -- Enable or disable a callback to receive joystick (dis)connection -- events -- -- Must only be called from the environment task. private type Joystick is tagged record Raw_Index : Enums.Joystick_ID := Enums.Joystick_1; end record; for Joystick_Button_State'Size use Interfaces.C.char'Size; for Joystick_Hat_State use (Centered => 0, Up => 1, Right => 2, Right_Up => 3, Down => 4, Right_Down => 6, Left => 8, Left_Up => 9, Left_Down => 12); for Joystick_Hat_State'Size use Interfaces.C.char'Size; for Connect_State use (Connected => 16#40001#, Disconnected => 16#40002#); for Connect_State'Size use Interfaces.C.int'Size; end Glfw.Input.Joysticks;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2013 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Glfw.Enums; package Glfw.Input.Joysticks is pragma Preelaborate; use type Interfaces.C.C_float; type Joystick_Index is range 1 .. 16; -- GLFW supports up to 16 joysticks; they are indexed from 1 to 16 type Joystick is tagged private; -- A Joystick object will link to the first joystick by default type Axis_Position is new Interfaces.C.C_float range -1.0 .. 1.0; type Axis_Positions is array (Positive range <>) of aliased Axis_Position; type Joystick_Button_State is new Button_State; type Joystick_Button_States is array (Positive range <>) of aliased Joystick_Button_State; subtype Gamepad_Button_Index is Positive range 1 .. 15; subtype Gamepad_Axis_Index is Positive range 1 .. 6; type Joystick_Gamepad_State is record Buttons : Joystick_Button_States (Gamepad_Button_Index); Axes : Axis_Positions (Gamepad_Axis_Index); end record with Convention => C; type Joystick_Hat_State is (Centered, Up, Right, Right_Up, Down, Right_Down, Left, Left_Up, Left_Down); type Joystick_Hat_States is array (Positive range <>) of aliased Joystick_Hat_State; type Connect_State is (Connected, Disconnected); function Index (Source : Joystick) return Joystick_Index; procedure Set_Index (Target : in out Joystick; Value : Joystick_Index); function Present (Source : Joystick) return Boolean; function Is_Gamepad (Source : Joystick) return Boolean; function Gamepad_Name (Source : Joystick) return String; function Gamepad_State (Source : Joystick) return Joystick_Gamepad_State; function Joystick_Name (Source : Joystick) return String; function Joystick_GUID (Source : Joystick) return String; procedure Update_Gamepad_Mappings (Mappings : String); function Positions (Source : Joystick) return Axis_Positions; function Button_States (Source : Joystick) return Joystick_Button_States; function Hat_States (Source : Joystick) return Joystick_Hat_States; type Joystick_Callback is access procedure (Source : Joystick; State : Connect_State); procedure Set_Callback (Callback : Joystick_Callback); -- Enable or disable a callback to receive joystick (dis)connection -- events -- -- Must only be called from the environment task. private type Joystick is tagged record Raw_Index : Enums.Joystick_ID := Enums.Joystick_1; end record; for Joystick_Button_State'Size use Interfaces.C.char'Size; for Joystick_Hat_State use (Centered => 0, Up => 1, Right => 2, Right_Up => 3, Down => 4, Right_Down => 6, Left => 8, Left_Up => 9, Left_Down => 12); for Joystick_Hat_State'Size use Interfaces.C.char'Size; for Connect_State use (Connected => 16#40001#, Disconnected => 16#40002#); for Connect_State'Size use Interfaces.C.int'Size; end Glfw.Input.Joysticks;
Use named subtype for indices of gamepad button and axis arrays
glfw: Use named subtype for indices of gamepad button and axis arrays Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
f4a75816616c4b7de4bd1ab24692604b6c9d58d3
regtests/gen-integration-tests.ads
regtests/gen-integration-tests.ads
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test dynamo create-project command --lib. procedure Test_Create_Lib_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist with exclude support command. procedure Test_Dist_Exclude (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with serialization code. procedure Test_Generate_Zargo_Serialization (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014, 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 Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test dynamo create-project command --lib. procedure Test_Create_Lib_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist with exclude support command. procedure Test_Dist_Exclude (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with serialization code. procedure Test_Generate_Zargo_Serialization (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
Remove Set_Up and Tear_Down procedures
Remove Set_Up and Tear_Down procedures
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
fe9e26f1da4fbb7772443d968ba21c896d7b6a35
regtests/util-serialize-io-json-tests.adb
regtests/util-serialize-io-json-tests.adb
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Ada.Characters.Wide_Wide_Latin_1; with Ada.Calendar.Formatting; with Util.Test_Caller; with Util.Log.Loggers; with Util.Streams.Files; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write", Test_Output'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; begin P.Parse_String (Content); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); Check_Parse_Error ("{ ""person"":""\uze""}"); Check_Parse_Error ("{ ""person"":""\u012-""}"); Check_Parse_Error ("{ ""person"":""\u012G""}"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; begin P.Parse_String (Content); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); Check_Parse ("{""person"":""asf"",""age"":""2""}"); Check_Parse ("{ ""person"":""\u0123""}"); Check_Parse ("{ ""person"":""\u4567""}"); Check_Parse ("{ ""person"":""\u89ab""}"); Check_Parse ("{ ""person"":""\ucdef""}"); Check_Parse ("{ ""person"":""\u1CDE""}"); Check_Parse ("{ ""person"":""\u2ABF""}"); end Test_Parser; -- ------------------------------ -- Generate some output stream for the test. -- ------------------------------ procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is Name : Ada.Strings.Unbounded.Unbounded_String; Wide : constant Wide_Wide_String := Ada.Characters.Wide_Wide_Latin_1.CR & Ada.Characters.Wide_Wide_Latin_1.LF & Ada.Characters.Wide_Wide_Latin_1.HT & Wide_Wide_Character'Val (16#080#) & Wide_Wide_Character'Val (16#1fC#) & Wide_Wide_Character'Val (16#20AC#) & -- Euro sign Wide_Wide_Character'Val (16#2acbf#); T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0); begin Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen"); Stream.Start_Document; Stream.Start_Entity ("root"); Stream.Start_Entity ("person"); Stream.Write_Attribute ("id", 1); Stream.Write_Attribute ("name", Name); Stream.Write_Entity ("name", Name); Stream.Write_Entity ("gender", "female"); Stream.Write_Entity ("volunteer", True); Stream.Write_Entity ("age", 17); Stream.Write_Entity ("date", T); Stream.Write_Wide_Entity ("skin", "olive skin"); Stream.Start_Array ("badges"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "hunter"); Stream.End_Entity ("badge"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "archery"); Stream.End_Entity ("badge"); Stream.End_Array ("badges"); Stream.Start_Entity ("district"); Stream.Write_Attribute ("id", 12); Stream.Write_Wide_Attribute ("industry", "Coal mining"); Stream.Write_Attribute ("state", "<destroyed>"); Stream.Write_Long_Entity ("members", 10_000); Stream.Write_Entity ("description", "<TBW>&"""); Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+="); Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+="); Stream.Write_Wide_Entity ("wide", Wide); Stream.End_Entity ("district"); Stream.End_Entity ("person"); Stream.End_Entity ("root"); Stream.End_Document; end Write_Stream; -- ------------------------------ -- Test the JSON output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Buffer : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.JSON.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000); Stream.Initialize (Output => Buffer'Unchecked_Access); Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "JSON output serialization"); end Test_Output; end Util.Serialize.IO.JSON.Tests;
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Ada.Characters.Wide_Wide_Latin_1; with Ada.Calendar.Formatting; with Util.Test_Caller; with Util.Log.Loggers; with Util.Streams.Files; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write", Test_Output'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; begin P.Parse_String (Content); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); Check_Parse_Error ("{ ""person"":""\uze""}"); Check_Parse_Error ("{ ""person"":""\u012-""}"); Check_Parse_Error ("{ ""person"":""\u012G""}"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; begin P.Parse_String (Content); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); Check_Parse ("{""person"":""asf"",""age"":""2""}"); Check_Parse ("{ ""person"":""\u0123""}"); Check_Parse ("{ ""person"":""\u4567""}"); Check_Parse ("{ ""person"":""\u89ab""}"); Check_Parse ("{ ""person"":""\ucdef""}"); Check_Parse ("{ ""person"":""\u1CDE""}"); Check_Parse ("{ ""person"":""\u2ABF""}"); Check_Parse ("[{ ""person"":""\u2ABF""}]"); end Test_Parser; -- ------------------------------ -- Generate some output stream for the test. -- ------------------------------ procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is Name : Ada.Strings.Unbounded.Unbounded_String; Wide : constant Wide_Wide_String := Ada.Characters.Wide_Wide_Latin_1.CR & Ada.Characters.Wide_Wide_Latin_1.LF & Ada.Characters.Wide_Wide_Latin_1.HT & Wide_Wide_Character'Val (16#080#) & Wide_Wide_Character'Val (16#1fC#) & Wide_Wide_Character'Val (16#20AC#) & -- Euro sign Wide_Wide_Character'Val (16#2acbf#); T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0); begin Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen"); Stream.Start_Document; Stream.Start_Entity ("root"); Stream.Start_Entity ("person"); Stream.Write_Attribute ("id", 1); Stream.Write_Attribute ("name", Name); Stream.Write_Entity ("name", Name); Stream.Write_Entity ("gender", "female"); Stream.Write_Entity ("volunteer", True); Stream.Write_Entity ("age", 17); Stream.Write_Entity ("date", T); Stream.Write_Wide_Entity ("skin", "olive skin"); Stream.Start_Array ("badges"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "hunter"); Stream.End_Entity ("badge"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "archery"); Stream.End_Entity ("badge"); Stream.End_Array ("badges"); Stream.Start_Entity ("district"); Stream.Write_Attribute ("id", 12); Stream.Write_Wide_Attribute ("industry", "Coal mining"); Stream.Write_Attribute ("state", "<destroyed>"); Stream.Write_Long_Entity ("members", 10_000); Stream.Write_Entity ("description", "<TBW>&"""); Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+="); Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+="); Stream.Write_Wide_Entity ("wide", Wide); Stream.End_Entity ("district"); Stream.End_Entity ("person"); Stream.End_Entity ("root"); Stream.End_Document; end Write_Stream; -- ------------------------------ -- Test the JSON output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Buffer : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.JSON.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000); Stream.Initialize (Output => Buffer'Unchecked_Access); Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "JSON output serialization"); end Test_Output; end Util.Serialize.IO.JSON.Tests;
Add another test case for the JSON parser test
Add another test case for the JSON parser test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0f19d08c712da8ff8b53c75430833fb293fce97c
regtests/security-testsuite.adb
regtests/security-testsuite.adb
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Openid.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; package body Security.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Security.Openid.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.OpenID.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; package body Security.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Security.OpenID.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-security
00f9ad63e0fd75cc0899e74338c77d8fbb96ea64
src/babel-strategies.ads
src/babel-strategies.ads
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014, 2015, 2016 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Listeners; with Babel.Files; with Babel.Files.Queues; with Babel.Files.Buffers; with Babel.Streams.Refs; with Babel.Stores; with Babel.Filters; with Babel.Base; with Babel.Base.Text; package Babel.Strategies is type Strategy_Type is abstract tagged limited private; type Strategy_Type_Access is access all Strategy_Type'Class; -- Allocate a buffer to read the file content. function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access; -- Release the buffer that was allocated by Allocate_Buffer. procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access); -- Returns true if there is a directory that must be processed by the current strategy. function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract; -- Get the next directory that must be processed by the strategy. procedure Peek_Directory (Strategy : in out Strategy_Type; Directory : out Babel.Files.Directory_Type) is abstract; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class); -- Scan the directories which are defined in the directory queue and -- use the file container to scan the files and directories. procedure Scan (Strategy : in out Strategy_Type; Queue : in out Babel.Files.Queues.Directory_Queue; Container : in out Babel.Files.File_Container'Class); -- Read the file from the read store into the local buffer. procedure Read_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Into : in Babel.Files.Buffers.Buffer_Access); -- Write the file from the local buffer into the write store. procedure Write_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in Babel.Files.Buffers.Buffer_Access); -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in out Strategy_Type; File : in Babel.Files.File_Type; Content : in out Babel.Files.Buffers.Buffer_Access); procedure Execute (Strategy : in out Strategy_Type) is abstract; -- Set the file filters that will be used when scanning the read store. procedure Set_Filters (Strategy : in out Strategy_Type; Filters : in Babel.Filters.Filter_Type_Access); -- Set the read and write stores that the strategy will use. procedure Set_Stores (Strategy : in out Strategy_Type; Read : in Babel.Stores.Store_Type_Access; Write : in Babel.Stores.Store_Type_Access); -- Set the buffer pool to be used by Allocate_Buffer. procedure Set_Buffers (Strategy : in out Strategy_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access); -- Set the listeners to inform about changes. procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List); -- Set the database for use by the strategy. procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access); private type Strategy_Type is abstract tagged limited record Read_Store : Babel.Stores.Store_Type_Access; Write_Store : Babel.Stores.Store_Type_Access; Filters : Babel.Filters.Filter_Type_Access; Buffers : Babel.Files.Buffers.Buffer_Pool_Access; Listeners : access Util.Listeners.List; -- Database : Babel.Base.Database_Access; Database : Babel.Base.Text.Text_Database; end record; end Babel.Strategies;
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014, 2015, 2016 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Listeners; with Babel.Files; with Babel.Files.Queues; with Babel.Files.Buffers; with Babel.Streams.Refs; with Babel.Stores; with Babel.Filters; with Babel.Base; with Babel.Base.Text; package Babel.Strategies is type Strategy_Type is abstract tagged limited private; type Strategy_Type_Access is access all Strategy_Type'Class; -- Allocate a buffer to read the file content. function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access; -- Release the buffer that was allocated by Allocate_Buffer. procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access); -- Returns true if there is a directory that must be processed by the current strategy. function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract; -- Get the next directory that must be processed by the strategy. procedure Peek_Directory (Strategy : in out Strategy_Type; Directory : out Babel.Files.Directory_Type) is abstract; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class); -- Scan the directories which are defined in the directory queue and -- use the file container to scan the files and directories. procedure Scan (Strategy : in out Strategy_Type; Queue : in out Babel.Files.Queues.Directory_Queue; Container : in out Babel.Files.File_Container'Class); -- Read the file from the read store into the local buffer. procedure Read_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Stream : in out Babel.Streams.Refs.Stream_Ref); -- Write the file from the local buffer into the write store. procedure Write_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Stream : in Babel.Streams.Refs.Stream_Ref); -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in out Strategy_Type; File : in Babel.Files.File_Type; Stream : in Babel.Streams.Refs.Stream_Ref); procedure Execute (Strategy : in out Strategy_Type) is abstract; -- Set the file filters that will be used when scanning the read store. procedure Set_Filters (Strategy : in out Strategy_Type; Filters : in Babel.Filters.Filter_Type_Access); -- Set the read and write stores that the strategy will use. procedure Set_Stores (Strategy : in out Strategy_Type; Read : in Babel.Stores.Store_Type_Access; Write : in Babel.Stores.Store_Type_Access); -- Set the buffer pool to be used by Allocate_Buffer. procedure Set_Buffers (Strategy : in out Strategy_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access); -- Set the listeners to inform about changes. procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List); -- Set the database for use by the strategy. procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access); private type Strategy_Type is abstract tagged limited record Read_Store : Babel.Stores.Store_Type_Access; Write_Store : Babel.Stores.Store_Type_Access; Filters : Babel.Filters.Filter_Type_Access; Buffers : Babel.Files.Buffers.Buffer_Pool_Access; Listeners : access Util.Listeners.List; -- Database : Babel.Base.Database_Access; Database : Babel.Base.Text.Text_Database; end record; end Babel.Strategies;
Use a Babel.Streams.Refs.Stream_Ref for the Read_File and Write_File operations
Use a Babel.Streams.Refs.Stream_Ref for the Read_File and Write_File operations
Ada
apache-2.0
stcarrez/babel
145ad03a88a3e48e2f069ad6db606782c616e928
awa/plugins/awa-workspaces/src/awa-workspaces.ads
awa/plugins/awa-workspaces/src/awa-workspaces.ads
----------------------------------------------------------------------- -- awa-workspaces -- Module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The *workspaces* plugin defines a workspace area for other plugins. -- -- == Ada Beans == -- @include workspaces.xml -- -- == Data Model == -- @include Workspace.hbm.xml -- package AWA.Workspaces is end AWA.Workspaces;
----------------------------------------------------------------------- -- awa-workspaces -- Module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The *workspaces* plugin defines a workspace area for other plugins. -- The workspace is intended to link together all the data objects that an application -- manages for a given user or group of users. A workspace is a possible mechanism -- to provide and implement multi-tenancy in a web application. By using the workspace plugin, -- application data from different customers can be kept separate from each other in the -- same database. -- -- == Ada Beans == -- @include workspaces.xml -- -- == Data Model == -- @include Workspace.hbm.xml -- package AWA.Workspaces is end AWA.Workspaces;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
3b377ad664ccf172753368ccef540187db508762
src/security-controllers-roles.ads
src/security-controllers-roles.ads
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; with Security.Permissions; with Util.Beans.Objects; with Util.Serialize.IO.XML; package Security.Controllers.Roles is -- ------------------------------ -- Security Controller -- ------------------------------ -- The <b>Role_Controller</b> implements a simple role based permissions check. -- The permission is granted if the user has the role defined by the controller. type Role_Controller (Count : Positive) is limited new Controller with record Roles : Permissions.Role_Type_Array (1 .. Count); end record; type Role_Controller_Access is access all Role_Controller'Class; -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class) return Boolean; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last)); Count : Natural := 0; Manager : Security.Permissions.Permission_Manager_Access; end record; -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Security.Permissions.Permission_Manager_Access; package Reader_Config is Config : aliased Controller_Config; end Reader_Config; end Security.Controllers.Roles;
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; with Security.Permissions; with Util.Beans.Objects; with Util.Serialize.IO.XML; package Security.Controllers.Roles is -- ------------------------------ -- Security Controller -- ------------------------------ -- The <b>Role_Controller</b> implements a simple role based permissions check. -- The permission is granted if the user has the role defined by the controller. type Role_Controller (Count : Positive) is limited new Controller with record Roles : Permissions.Role_Type_Array (1 .. Count); end record; type Role_Controller_Access is access all Role_Controller'Class; -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last)); Count : Natural := 0; Manager : Security.Permissions.Permission_Manager_Access; end record; -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Security.Permissions.Permission_Manager_Access; package Reader_Config is Config : aliased Controller_Config; end Reader_Config; end Security.Controllers.Roles;
Add Permission parameter
Add Permission parameter
Ada
apache-2.0
stcarrez/ada-security
9084fad41abce45579cc614420de3143d881fad7
awa/src/aws/awa-mail-clients-aws_smtp.adb
awa/src/aws/awa-mail-clients-aws_smtp.adb
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); else Log.Info ("Disable send email to {0}", ""); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Self := Result; Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server, Port => Positive'Value (Port)); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); else Log.Info ("Disable send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Self := Result; Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server, Port => Positive'Value (Port)); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
Update the log if the mail is disabled
Update the log if the mail is disabled
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c6bb562661e829651d8b158201953b83f47a201e
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.Add_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 => Engine.Add_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => null; when Wiki.Nodes.N_BLOCKQUOTE => null; 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 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; -- ------------------------------ -- Add a section header in the document. -- ------------------------------ procedure Add_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 Add_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; -- ------------------------------ -- Add a link. -- ------------------------------ 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) is Exists : Boolean; URI : Unbounded_Wide_Wide_String; begin Document.Open_Paragraph; Document.Output.Start_Element ("a"); if Length (Title) > 0 then Document.Output.Write_Wide_Attribute ("title", Title); end if; if Length (Language) > 0 then Document.Output.Write_Wide_Attribute ("lang", Language); end if; Document.Links.Make_Page_Link (Link, URI, Exists); Document.Output.Write_Wide_Attribute ("href", URI); Document.Output.Write_Wide_Text (Name); Document.Output.End_Element ("a"); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ 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) is pragma Unreferenced (Position); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; begin Document.Open_Paragraph; Document.Output.Start_Element ("img"); if Length (Alt) > 0 then Document.Output.Write_Wide_Attribute ("alt", Alt); end if; if Length (Description) > 0 then Document.Output.Write_Wide_Attribute ("longdesc", Description); end if; Document.Links.Make_Image_Link (Link, URI, Width, Height); Document.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Document.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Document.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Document.Output.End_Element ("img"); end Add_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.Add_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.Add_Link (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; -- ------------------------------ -- Add a section header in the document. -- ------------------------------ procedure Add_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 Add_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_Unbounded_Wide_Value (Attr, "href"); URI : Unbounded_Wide_Wide_String; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); if Length (Title) > 0 then Document.Output.Write_Wide_Attribute ("title", Title); end if; if Length (Language) > 0 then Document.Output.Write_Wide_Attribute ("lang", Language); end if; Engine.Links.Make_Page_Link (Link, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); Engine.Output.Write_Wide_Text (Name); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Add an image. -- ------------------------------ 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) is pragma Unreferenced (Position); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; begin Document.Open_Paragraph; Document.Output.Start_Element ("img"); if Length (Alt) > 0 then Document.Output.Write_Wide_Attribute ("alt", Alt); end if; if Length (Description) > 0 then Document.Output.Write_Wide_Attribute ("longdesc", Description); end if; Document.Links.Make_Image_Link (Link, URI, Width, Height); Document.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Document.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Document.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Document.Output.End_Element ("img"); end Add_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;
Implement the Render_Link procedure and use it to render a N_LINK
Implement the Render_Link procedure and use it to render a N_LINK
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
fa86a8f7d81490bc4d3755dfb0e8f6d9d8a22aba
src/asf-views-facelets.adb
src/asf-views-facelets.adb
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 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.Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ASF.Views.Nodes.Reader; with Input_Sources.File; with Sax.Readers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; package body ASF.Views.Facelets is use ASF.Views.Nodes; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info, Name => ASF.Views.File_Info_Access); -- Find in the factory for the facelet with the given name. procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet); -- Load the facelet node tree by reading the facelet XHTML file. procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Update the factory to store the facelet node tree procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet); -- ------------------------------ -- Returns True if the facelet is null/empty. -- ------------------------------ function Is_Null (F : Facelet) return Boolean is begin return F.Root = null; end Is_Null; -- ------------------------------ -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. -- ------------------------------ procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Res : Facelet; Fname : constant Unbounded_String := To_Unbounded_String (Name); begin Log.Debug ("Find facelet {0}", Name); Find (Factory, Fname, Res); if Res.Root = null then Load (Factory, Name, Context, Res); if Res.Root = null then Result.Root := null; return; end if; Update (Factory, Fname, Res); end if; Result.Root := Res.Root; Result.File := Res.File; end Find_Facelet; -- ------------------------------ -- Create the component tree from the facelet view. -- ------------------------------ procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access) is Old : Unbounded_String; begin if View.Root /= null then Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.File.all), Previous => Old); View.Root.Build_Children (Parent => Root, Context => Context); Context.Set_Relative_Path (Path => Old); end if; end Build_View; -- ------------------------------ -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. -- ------------------------------ procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean) is begin Log.Info ("Set facelet search directory to: '{0}'", Paths); Factory.Factory := Components; Factory.Paths := To_Unbounded_String (Paths); Factory.Ignore_White_Spaces := Ignore_White_Spaces; Factory.Ignore_Empty_Lines := Ignore_Empty_Lines; Factory.Escape_Unknown_Tags := Escape_Unknown_Tags; end Initialize; -- ------------------------------ -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. -- ------------------------------ function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String is begin return Util.Files.Find_File_Path (Name, To_String (Factory.Paths)); end Find_Facelet_Path; -- ------------------------------ -- Find in the factory for the facelet with the given name. -- ------------------------------ procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet) is use Ada.Directories; use Ada.Calendar; begin Result.Root := null; Result := Factory.Map.Find (Name); if Result.Root /= null and then Modification_Time (Result.File.Path) > Result.Modify_Time then Result.Root := null; Log.Info ("Ignoring cache because file '{0}' was modified", Result.File.Path); end if; end Find; -- ------------------------------ -- Load the facelet node tree by reading the facelet XHTML file. -- ------------------------------ procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Path : constant String := Find_Facelet_Path (Factory, Name); begin if Path = "" or else not Ada.Directories.Exists (Path) then Log.Warn ("Cannot read '{0}': file does not exist", Path); Result.Root := null; return; end if; declare RPos : constant Integer := Path'Last - Name'Length + 1; File : File_Info_Access; Reader : ASF.Views.Nodes.Reader.Xhtml_Reader; Read : Input_Sources.File.File_Input; Mtime : Ada.Calendar.Time; Ctx : aliased EL.Contexts.Default.Default_Context; begin if Rpos <= Path'First then File := Create_File_Info (Path, Path'First); else File := Create_File_Info (Path, RPos); end if; Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name, Natural'Image (File.Relative_Pos)); Ctx.Set_Function_Mapper (Context.Get_Function_Mapper); Mtime := Ada.Directories.Modification_Time (Path); Input_Sources.File.Open (Path, Read); -- If True, xmlns:* attributes will be reported in Start_Element Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False); Reader.Set_Feature (Sax.Readers.Validation_Feature, False); Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces); Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags); Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines); begin Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access); exception when ASF.Views.Nodes.Reader.Parsing_Error => Free (File); when E : others => Free (File); Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path, Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); end; Result.Root := Reader.Get_Root; Result.File := File; if File = null then if Result.Root /= null then Result.Root.Delete; end if; Result.Root := null; else Result.Modify_Time := Mtime; end if; Input_Sources.File.Close (Read); end; end Load; -- ------------------------------ -- Update the factory to store the facelet node tree -- ------------------------------ procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet) is begin Factory.Map.Insert (Name, Item); end Update; -- ------------------------------ -- Clear the facelet cache -- ------------------------------ procedure Clear_Cache (Factory : in out Facelet_Factory) is begin Log.Info ("Clearing facelet cache"); Factory.Map.Clear; end Clear_Cache; protected body Facelet_Cache is -- ------------------------------ -- Find the facelet entry associated with the given name. -- ------------------------------ function Find (Name : in Unbounded_String) return Facelet is Pos : constant Facelet_Maps.Cursor := Map.Find (Name); begin if Facelet_Maps.Has_Element (Pos) then return Element (Pos); else return Empty; end if; end Find; -- ------------------------------ -- Insert or replace the facelet entry associated with the given name. -- ------------------------------ procedure Insert (Name : in Unbounded_String; Item : in Facelet) is begin Map.Include (Name, Item); end Insert; -- ------------------------------ -- Clear the cache. -- ------------------------------ procedure Clear is begin loop declare Pos : Facelet_Maps.Cursor := Map.First; Node : Facelet; begin exit when not Has_Element (Pos); Node := Element (Pos); Map.Delete (Pos); Free (Node.File); ASF.Views.Nodes.Destroy (Node.Root); end; end loop; end Clear; end Facelet_Cache; -- ------------------------------ -- Free the storage held by the factory cache. -- ------------------------------ overriding procedure Finalize (Factory : in out Facelet_Factory) is begin Factory.Clear_Cache; end Finalize; end ASF.Views.Facelets;
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 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.Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ASF.Views.Nodes.Reader; with Input_Sources.File; with Sax.Readers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; package body ASF.Views.Facelets is use ASF.Views.Nodes; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info, Name => ASF.Views.File_Info_Access); -- Find in the factory for the facelet with the given name. procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet); -- Load the facelet node tree by reading the facelet XHTML file. procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Update the factory to store the facelet node tree procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet); -- ------------------------------ -- Returns True if the facelet is null/empty. -- ------------------------------ function Is_Null (F : Facelet) return Boolean is begin return F.Root = null; end Is_Null; -- ------------------------------ -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. -- ------------------------------ procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Res : Facelet; Fname : constant Unbounded_String := To_Unbounded_String (Name); begin Log.Debug ("Find facelet {0}", Name); Find (Factory, Fname, Res); if Res.Root = null then Load (Factory, Name, Context, Res); if Res.Root = null then Result.Root := null; return; end if; Update (Factory, Fname, Res); end if; Result.Root := Res.Root; Result.File := Res.File; end Find_Facelet; -- ------------------------------ -- Create the component tree from the facelet view. -- ------------------------------ procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access) is Old : Unbounded_String; begin if View.Root /= null then Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.File.all), Previous => Old); View.Root.Build_Children (Parent => Root, Context => Context); Context.Set_Relative_Path (Path => Old); end if; end Build_View; -- ------------------------------ -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. -- ------------------------------ procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean) is begin Log.Info ("Set facelet search directory to: '{0}'", Paths); Factory.Factory := Components; Factory.Paths := To_Unbounded_String (Paths); Factory.Ignore_White_Spaces := Ignore_White_Spaces; Factory.Ignore_Empty_Lines := Ignore_Empty_Lines; Factory.Escape_Unknown_Tags := Escape_Unknown_Tags; end Initialize; -- ------------------------------ -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. -- ------------------------------ function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String is begin return Util.Files.Find_File_Path (Name, To_String (Factory.Paths)); end Find_Facelet_Path; -- ------------------------------ -- Find in the factory for the facelet with the given name. -- ------------------------------ procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet) is use Ada.Directories; use Ada.Calendar; begin Result.Root := null; Result := Factory.Map.Find (Name); if Result.Root /= null and then Modification_Time (Result.File.Path) > Result.Modify_Time then Result.Root := null; Log.Info ("Ignoring cache because file '{0}' was modified", Result.File.Path); end if; end Find; -- ------------------------------ -- Load the facelet node tree by reading the facelet XHTML file. -- ------------------------------ procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Path : constant String := Find_Facelet_Path (Factory, Name); begin if Path = "" or else not Ada.Directories.Exists (Path) then Log.Warn ("Cannot read '{0}': file does not exist", Path); Result.Root := null; return; end if; declare Pos : constant Integer := Path'Last - Name'Length + 1; File : File_Info_Access; Reader : ASF.Views.Nodes.Reader.Xhtml_Reader; Read : Input_Sources.File.File_Input; Mtime : Ada.Calendar.Time; Ctx : aliased EL.Contexts.Default.Default_Context; begin if Pos <= Path'First then File := Create_File_Info (Path, Path'First); else File := Create_File_Info (Path, Pos); end if; Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name, Natural'Image (File.Relative_Pos)); Ctx.Set_Function_Mapper (Context.Get_Function_Mapper); Mtime := Ada.Directories.Modification_Time (Path); Input_Sources.File.Open (Path, Read); -- If True, xmlns:* attributes will be reported in Start_Element Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False); Reader.Set_Feature (Sax.Readers.Validation_Feature, False); Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces); Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags); Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines); begin Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access); exception when ASF.Views.Nodes.Reader.Parsing_Error => Free (File); when E : others => Free (File); Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path, Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); end; Result.Root := Reader.Get_Root; Result.File := File; if File = null then if Result.Root /= null then Result.Root.Delete; end if; Result.Root := null; else Result.Modify_Time := Mtime; end if; Input_Sources.File.Close (Read); end; end Load; -- ------------------------------ -- Update the factory to store the facelet node tree -- ------------------------------ procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet) is begin Factory.Map.Insert (Name, Item); end Update; -- ------------------------------ -- Clear the facelet cache -- ------------------------------ procedure Clear_Cache (Factory : in out Facelet_Factory) is begin Log.Info ("Clearing facelet cache"); Factory.Map.Clear; end Clear_Cache; protected body Facelet_Cache is -- ------------------------------ -- Find the facelet entry associated with the given name. -- ------------------------------ function Find (Name : in Unbounded_String) return Facelet is Pos : constant Facelet_Maps.Cursor := Map.Find (Name); begin if Facelet_Maps.Has_Element (Pos) then return Element (Pos); else return Empty; end if; end Find; -- ------------------------------ -- Insert or replace the facelet entry associated with the given name. -- ------------------------------ procedure Insert (Name : in Unbounded_String; Item : in Facelet) is begin Map.Include (Name, Item); end Insert; -- ------------------------------ -- Clear the cache. -- ------------------------------ procedure Clear is begin loop declare Pos : Facelet_Maps.Cursor := Map.First; Node : Facelet; begin exit when not Has_Element (Pos); Node := Element (Pos); Map.Delete (Pos); Free (Node.File); ASF.Views.Nodes.Destroy (Node.Root); end; end loop; end Clear; end Facelet_Cache; -- ------------------------------ -- Free the storage held by the factory cache. -- ------------------------------ overriding procedure Finalize (Factory : in out Facelet_Factory) is begin Factory.Clear_Cache; end Finalize; end ASF.Views.Facelets;
Rename RPos local variable into Pos
Rename RPos local variable into Pos
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
de2f77c2bff0219b738c1260e30c1eb4476deab3
tools/druss-gateways.adb
tools/druss-gateways.adb
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Basic; with Util.Strings; with Bbox.API; package body Druss.Gateways is use Ada.Strings.Unbounded; protected body Gateway_State is function Get_State return State_Type is begin return State; end Get_State; end Gateway_State; function "=" (Left, Right : in Gateway_Ref) return Boolean is begin return False; end "="; -- ------------------------------ -- Initalize the list of gateways from the property list. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector) is Count : constant Natural := Util.Properties.Basic.Integer_Property.Get (Config, "druss.bbox.count", 0); begin for I in 1 .. Count loop declare Gw : Gateway_Ref := Gateway_Refs.Create; Base : constant String := "druss.bbox." & Util.Strings.Image (I); begin Gw.Value.Ip := Config.Get (Base & ".ip"); Gw.Value.Images := Config.Get (Base & ".images"); Gw.Value.Passwd := Config.Get (Base & ".password"); List.Append (Gw); exception when Util.Properties.NO_PROPERTY => null; end; end loop; end Initialize; -- ------------------------------ -- Refresh the information by using the Bbox API. -- ------------------------------ procedure Refresh (Gateway : in out Gateway_Type) is Box : Bbox.API.Client_Type; begin if Gateway.State.Get_State = BUSY then return; end if; Box.Set_Server (To_String (Gateway.IP)); Box.Login (To_String (Gateway.Passwd)); Box.Get ("wan/ip", Gateway.Wan); Box.Get ("lan/ip", Gateway.Lan); Box.Get ("device", Gateway.Device); Box.Get ("wireless", Gateway.Wifi); end Refresh; -- ------------------------------ -- Refresh the information by using the Bbox API. -- ------------------------------ procedure Refresh (Gateway : in Gateway_Ref) is begin Gateway.Value.Refresh; end Refresh; -- ------------------------------ -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Gateway_Vector; Process : not null access procedure (G : in out Gateway_Type)) is begin for G of List loop Process (G.Value.all); end loop; end Iterate; end Druss.Gateways;
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Basic; with Util.Strings; with Util.Log.Loggers; with Bbox.API; package body Druss.Gateways is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Gateways"); protected body Gateway_State is function Get_State return State_Type is begin return State; end Get_State; end Gateway_State; function "=" (Left, Right : in Gateway_Ref) return Boolean is begin if Left.Value = Right.Value then return True; elsif Left.Is_Null or Right.Is_Null then return False; else return Left.Value.IP = Right.Value.IP; end if; end "="; -- ------------------------------ -- Initalize the list of gateways from the property list. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector) is Count : constant Natural := Util.Properties.Basic.Integer_Property.Get (Config, "druss.bbox.count", 0); begin for I in 1 .. Count loop declare Gw : constant Gateway_Ref := Gateway_Refs.Create; Base : constant String := "druss.bbox." & Util.Strings.Image (I); begin Gw.Value.Ip := Config.Get (Base & ".ip"); if Config.Exists (Base & ".images") then Gw.Value.Images := Config.Get (Base & ".images"); end if; Gw.Value.Passwd := Config.Get (Base & ".password"); Gw.Value.Serial := Config.Get (Base & ".serial"); List.Append (Gw); exception when Util.Properties.NO_PROPERTY => Log.Debug ("Ignoring gatway {0}", Base); end; end loop; end Initialize; -- ------------------------------ -- Save the list of gateways. -- ------------------------------ procedure Save_Gateways (Config : in out Util.Properties.Manager; List : in Druss.Gateways.Gateway_Vector) is Pos : Natural := 0; begin for Gw of List loop Pos := Pos + 1; declare Base : constant String := "druss.bbox." & Util.Strings.Image (Pos); begin Config.Set (Base & ".ip", Gw.Value.Ip); Config.Set (Base & ".password", Gw.Value.Passwd); Config.Set (Base & ".serial", Gw.Value.Serial); exception when Util.Properties.NO_PROPERTY => null; end; end loop; Util.Properties.Basic.Integer_Property.Set (Config, "druss.bbox.count", Pos); end Save_Gateways; -- ------------------------------ -- Refresh the information by using the Bbox API. -- ------------------------------ procedure Refresh (Gateway : in out Gateway_Type) is Box : Bbox.API.Client_Type; begin if Gateway.State.Get_State = BUSY then return; end if; Box.Set_Server (To_String (Gateway.IP)); if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then Box.Login (To_String (Gateway.Passwd)); end if; Box.Get ("wan/ip", Gateway.Wan); Box.Get ("lan/ip", Gateway.Lan); Box.Get ("device", Gateway.Device); Box.Get ("wireless", Gateway.Wifi); if Gateway.Device.Exists ("device.serialnumber") then Gateway.Serial := Gateway.Device.Get ("device.serialnumber"); end if; end Refresh; -- ------------------------------ -- Refresh the information by using the Bbox API. -- ------------------------------ procedure Refresh (Gateway : in Gateway_Ref) is begin Gateway.Value.Refresh; end Refresh; -- ------------------------------ -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Gateway_Vector; Process : not null access procedure (G : in out Gateway_Type)) is begin for G of List loop Process (G.Value.all); end loop; end Iterate; Null_Gateway : Gateway_Ref; -- ------------------------------ -- Find the gateway with the given IP address. -- ------------------------------ function Find_IP (List : in Gateway_Vector; IP : in String) return Gateway_Ref is begin for G of List loop if G.Value.IP = IP then return G; end if; end loop; -- raise Not_Found; return Null_Gateway; end Find_IP; end Druss.Gateways;
Implement the Find_IP operation Implement the Save_Gateways operation
Implement the Find_IP operation Implement the Save_Gateways operation
Ada
apache-2.0
stcarrez/bbox-ada-api
d5e106f85f0e7d90dcce1d6255564eac3de16062
regtests/util-encoders-tests.adb
regtests/util-encoders-tests.adb
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Tests; with Util.Measures; with Util.Strings.Transforms; with Ada.Text_IO; with Util.Encoders.SHA1; with Util.Encoders.HMAC.SHA1; -- with Util.Log.Loggers; package body Util.Encoders.Tests is use Util.Tests; -- use Util.Log; -- -- Log : constant Loggers.Logger := Loggers.Create ("Util.Encoders.Tests"); package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Encoders.Base16.Encode", Test_Hex'Access); Caller.Add_Test (Suite, "Test Util.Encoders.Base16.Decode", Test_Hex'Access); Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Encode", Test_Base64_Encode'Access); Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Decode", Test_Base64_Decode'Access); Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Benchmark", Test_Base64_Benchmark'Access); Caller.Add_Test (Suite, "Test Util.Encoders.SHA1.Encode", Test_SHA1_Encode'Access); Caller.Add_Test (Suite, "Test Util.Encoders.SHA1.Benchmark", Test_SHA1_Benchmark'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test1)", Test_HMAC_SHA1_RFC2202_T1'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test2)", Test_HMAC_SHA1_RFC2202_T2'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test3)", Test_HMAC_SHA1_RFC2202_T3'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test4)", Test_HMAC_SHA1_RFC2202_T4'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test5)", Test_HMAC_SHA1_RFC2202_T5'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test6)", Test_HMAC_SHA1_RFC2202_T6'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test7)", Test_HMAC_SHA1_RFC2202_T7'Access); end Add_Tests; procedure Test_Base64_Encode (T : in out Test) is C : constant Util.Encoders.Encoder := Create ("base64"); begin Assert_Equals (T, "YQ==", Util.Encoders.Encode (C, "a")); Assert_Equals (T, "fA==", Util.Encoders.Encode (C, "|")); Assert_Equals (T, "fHw=", Util.Encoders.Encode (C, "||")); Assert_Equals (T, "fH5+", Util.Encoders.Encode (C, "|~~")); end Test_Base64_Encode; procedure Test_Base64_Decode (T : in out Test) is C : Util.Encoders.Encoder := Create ("base64"); begin Assert_Equals (T, "a", Util.Encoders.Decode (C, "YQ==")); Assert_Equals (T, "|", Util.Encoders.Decode (C, "fA==")); Assert_Equals (T, "||", Util.Encoders.Decode (C, "fHw=")); Assert_Equals (T, "|~~", Util.Encoders.Decode (C, "fH5+")); Test_Encoder (T, C); end Test_Base64_Decode; procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder) is begin for I in 1 .. 334 loop declare Pattern : String (1 .. I); begin for J in Pattern'Range loop Pattern (J) := Character'Val (((J + I) mod 63) + 32); end loop; declare E : constant String := Util.Encoders.Encode (C, Pattern); D : constant String := Util.Encoders.Decode (C, E); begin Assert_Equals (T, Pattern, D, "Encoding failed for length " & Integer'Image (I)); end; exception when others => Ada.Text_IO.Put_Line ("Error at index " & Integer'Image (I)); raise; end; end loop; end Test_Encoder; procedure Test_Hex (T : in out Test) is C : Util.Encoders.Encoder := Create ("hex"); begin Assert_Equals (T, "41424344", Util.Encoders.Encode(C, "ABCD")); Assert_Equals (T, "ABCD", Util.Encoders.Decode (C, "41424344")); Test_Encoder (T, C); end Test_Hex; procedure Test_Base64_Benchmark (T : in out Test) is pragma Unreferenced (T); C : constant Util.Encoders.Encoder := Create ("base64"); S : constant String (1 .. 1_024) := (others => 'a'); begin declare T : Util.Measures.Stamp; R : constant String := Util.Encoders.Encode (C, S); pragma Unreferenced (R); begin Util.Measures.Report (T, "Base64 encode 1024 bytes"); end; end Test_Base64_Benchmark; procedure Test_SHA1_Encode (T : in out Test) is C : Util.Encoders.SHA1.Context; Hash : Util.Encoders.SHA1.Digest; procedure Check_Hash (Value : in String; Expect : in String) is J, N : Natural; Ctx : Util.Encoders.SHA1.Context; begin for I in 1 .. Value'Length loop J := Value'First; while J <= Value'Last loop if J + I <= Value'Last then N := J + I; else N := Value'Last; end if; Util.Encoders.SHA1.Update (Ctx, Value (J .. N)); J := N + 1; end loop; Util.Encoders.SHA1.Finish (Ctx, Hash); Assert_Equals (T, Expect, Hash, "Invalid hash for: " & Value); end loop; end Check_Hash; begin Util.Encoders.SHA1.Update (C, "a"); Util.Encoders.SHA1.Finish (C, Hash); Assert_Equals (T, "86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8", Hash, "Invalid hash for 'a'"); Check_Hash ("ut", "E746699D3947443D84DAD1E0C58BF7AD34712438"); Check_Hash ("Uti", "2C669751BDC4929377245F5EEBEAED1CE4DA8A45"); Check_Hash ("Util", "4C31156EFED35EE7814650F8971C3698059440E3"); Check_Hash ("Util.Encoders", "7DB6007AD8BAEA7C167FF2AE06C9F50A4645F971"); Check_Hash ("e746699d3947443d84dad1e0c58bf7ad347124382C669751BDC492937" & "7245F5EEBEAED1CE4DA8A45", "875C9C0DE4CE91ED8F432DD02B5BB40CD35DAACD"); end Test_SHA1_Encode; -- ------------------------------ -- Benchmark test for SHA1 -- ------------------------------ procedure Test_SHA1_Benchmark (T : in out Test) is pragma Unreferenced (T); Hash : Util.Encoders.SHA1.Digest; Sizes : constant array (1 .. 6) of Positive := (1, 10, 100, 1000, 10000, 100000); begin for I in Sizes'Range loop declare Size : constant Positive := Sizes (I); S : constant String (1 .. Size) := (others => '0'); T1 : Util.Measures.Stamp; C : Util.Encoders.SHA1.Context; begin Util.Encoders.SHA1.Update (C, S); Util.Encoders.SHA1.Finish (C, Hash); Util.Measures.Report (T1, "Encode SHA1" & Integer'Image (Size) & " bytes"); end; end loop; end Test_SHA1_Benchmark; procedure Check_HMAC (T : in out Test'Class; Key : in String; Value : in String; Expect : in String) is H : constant String := Util.Encoders.HMAC.SHA1.Sign (Key, Value); begin Assert_Equals (T, Expect, Util.Strings.Transforms.To_Lower_Case (H), "Invalid HMAC-SHA1"); end Check_HMAC; -- ------------------------------ -- Test HMAC-SHA1 -- ------------------------------ procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test) is Key : constant String (1 .. 20) := (others => Character'Val (16#0b#)); begin Check_HMAC (T, Key, "Hi There", "b617318655057264e28bc0b6fb378c8ef146be00"); end Test_HMAC_SHA1_RFC2202_T1; procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test) is begin Check_HMAC (T, "Jefe", "what do ya want for nothing?", "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"); end Test_HMAC_SHA1_RFC2202_T2; procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test) is Key : constant String (1 .. 20) := (others => Character'Val (16#aa#)); Data : constant String (1 .. 50) := (others => Character'Val (16#dd#)); begin Check_HMAC (T, Key, Data, "125d7342b9ac11cd91a39af48aa17b4f63f175d3"); end Test_HMAC_SHA1_RFC2202_T3; procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test) is C : constant Util.Encoders.Encoder := Create ("hex"); Key : constant String := Util.Encoders.Decode (C, "0102030405060708090a0b0c0d0e0f10111213141516171819"); Data : constant String (1 .. 50) := (others => Character'Val (16#cd#)); begin Check_HMAC (T, Key, Data, "4c9007f4026250c6bc8414f9bf50c86c2d7235da"); end Test_HMAC_SHA1_RFC2202_T4; procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test) is Key : constant String (1 .. 20) := (others => Character'Val (16#0c#)); begin -- RFC2202 test case 5 but without truncation... Check_HMAC (T, Key, "Test With Truncation", "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04"); end Test_HMAC_SHA1_RFC2202_T5; procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test) is Key : constant String (1 .. 80) := (others => Character'Val (16#aa#)); begin Check_HMAC (T, Key, "Test Using Larger Than Block-Size Key - Hash Key First", "aa4ae5e15272d00e95705637ce8a3b55ed402112"); end Test_HMAC_SHA1_RFC2202_T6; procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test) is Key : constant String (1 .. 80) := (others => Character'Val (16#Aa#)); begin Check_HMAC (T, Key, "Test Using Larger Than Block-Size Key and Larger " & "Than One Block-Size Data", "e8e99d0f45237d786d6bbaa7965c7808bbff1a91"); end Test_HMAC_SHA1_RFC2202_T7; end Util.Encoders.Tests;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with Util.Strings.Transforms; with Ada.Text_IO; with Util.Encoders.SHA1; with Util.Encoders.HMAC.SHA1; package body Util.Encoders.Tests is use Util.Tests; -- use Util.Log; -- -- Log : constant Loggers.Logger := Loggers.Create ("Util.Encoders.Tests"); procedure Check_HMAC (T : in out Test'Class; Key : in String; Value : in String; Expect : in String); package Caller is new Util.Test_Caller (Test, "Encoders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Encoders.Base16.Encode", Test_Hex'Access); Caller.Add_Test (Suite, "Test Util.Encoders.Base16.Decode", Test_Hex'Access); Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Encode", Test_Base64_Encode'Access); Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Decode", Test_Base64_Decode'Access); Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Benchmark", Test_Base64_Benchmark'Access); Caller.Add_Test (Suite, "Test Util.Encoders.SHA1.Encode", Test_SHA1_Encode'Access); Caller.Add_Test (Suite, "Test Util.Encoders.SHA1.Benchmark", Test_SHA1_Benchmark'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test1)", Test_HMAC_SHA1_RFC2202_T1'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test2)", Test_HMAC_SHA1_RFC2202_T2'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test3)", Test_HMAC_SHA1_RFC2202_T3'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test4)", Test_HMAC_SHA1_RFC2202_T4'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test5)", Test_HMAC_SHA1_RFC2202_T5'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test6)", Test_HMAC_SHA1_RFC2202_T6'Access); Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test7)", Test_HMAC_SHA1_RFC2202_T7'Access); end Add_Tests; procedure Test_Base64_Encode (T : in out Test) is C : constant Util.Encoders.Encoder := Create ("base64"); begin Assert_Equals (T, "YQ==", Util.Encoders.Encode (C, "a")); Assert_Equals (T, "fA==", Util.Encoders.Encode (C, "|")); Assert_Equals (T, "fHw=", Util.Encoders.Encode (C, "||")); Assert_Equals (T, "fH5+", Util.Encoders.Encode (C, "|~~")); end Test_Base64_Encode; procedure Test_Base64_Decode (T : in out Test) is C : Util.Encoders.Encoder := Create ("base64"); begin Assert_Equals (T, "a", Util.Encoders.Decode (C, "YQ==")); Assert_Equals (T, "|", Util.Encoders.Decode (C, "fA==")); Assert_Equals (T, "||", Util.Encoders.Decode (C, "fHw=")); Assert_Equals (T, "|~~", Util.Encoders.Decode (C, "fH5+")); Test_Encoder (T, C); end Test_Base64_Decode; procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder) is begin for I in 1 .. 334 loop declare Pattern : String (1 .. I); begin for J in Pattern'Range loop Pattern (J) := Character'Val (((J + I) mod 63) + 32); end loop; declare E : constant String := Util.Encoders.Encode (C, Pattern); D : constant String := Util.Encoders.Decode (C, E); begin Assert_Equals (T, Pattern, D, "Encoding failed for length " & Integer'Image (I)); end; exception when others => Ada.Text_IO.Put_Line ("Error at index " & Integer'Image (I)); raise; end; end loop; end Test_Encoder; procedure Test_Hex (T : in out Test) is C : Util.Encoders.Encoder := Create ("hex"); begin Assert_Equals (T, "41424344", Util.Encoders.Encode (C, "ABCD")); Assert_Equals (T, "ABCD", Util.Encoders.Decode (C, "41424344")); Test_Encoder (T, C); end Test_Hex; procedure Test_Base64_Benchmark (T : in out Test) is pragma Unreferenced (T); C : constant Util.Encoders.Encoder := Create ("base64"); S : constant String (1 .. 1_024) := (others => 'a'); begin declare T : Util.Measures.Stamp; R : constant String := Util.Encoders.Encode (C, S); pragma Unreferenced (R); begin Util.Measures.Report (T, "Base64 encode 1024 bytes"); end; end Test_Base64_Benchmark; procedure Test_SHA1_Encode (T : in out Test) is procedure Check_Hash (Value : in String; Expect : in String); C : Util.Encoders.SHA1.Context; Hash : Util.Encoders.SHA1.Digest; procedure Check_Hash (Value : in String; Expect : in String) is J, N : Natural; Ctx : Util.Encoders.SHA1.Context; begin for I in 1 .. Value'Length loop J := Value'First; while J <= Value'Last loop if J + I <= Value'Last then N := J + I; else N := Value'Last; end if; Util.Encoders.SHA1.Update (Ctx, Value (J .. N)); J := N + 1; end loop; Util.Encoders.SHA1.Finish (Ctx, Hash); Assert_Equals (T, Expect, Hash, "Invalid hash for: " & Value); end loop; end Check_Hash; begin Util.Encoders.SHA1.Update (C, "a"); Util.Encoders.SHA1.Finish (C, Hash); Assert_Equals (T, "86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8", Hash, "Invalid hash for 'a'"); Check_Hash ("ut", "E746699D3947443D84DAD1E0C58BF7AD34712438"); Check_Hash ("Uti", "2C669751BDC4929377245F5EEBEAED1CE4DA8A45"); Check_Hash ("Util", "4C31156EFED35EE7814650F8971C3698059440E3"); Check_Hash ("Util.Encoders", "7DB6007AD8BAEA7C167FF2AE06C9F50A4645F971"); Check_Hash ("e746699d3947443d84dad1e0c58bf7ad347124382C669751BDC492937" & "7245F5EEBEAED1CE4DA8A45", "875C9C0DE4CE91ED8F432DD02B5BB40CD35DAACD"); end Test_SHA1_Encode; -- ------------------------------ -- Benchmark test for SHA1 -- ------------------------------ procedure Test_SHA1_Benchmark (T : in out Test) is pragma Unreferenced (T); Hash : Util.Encoders.SHA1.Digest; Sizes : constant array (1 .. 6) of Positive := (1, 10, 100, 1000, 10000, 100000); begin for I in Sizes'Range loop declare Size : constant Positive := Sizes (I); S : constant String (1 .. Size) := (others => '0'); T1 : Util.Measures.Stamp; C : Util.Encoders.SHA1.Context; begin Util.Encoders.SHA1.Update (C, S); Util.Encoders.SHA1.Finish (C, Hash); Util.Measures.Report (T1, "Encode SHA1" & Integer'Image (Size) & " bytes"); end; end loop; end Test_SHA1_Benchmark; procedure Check_HMAC (T : in out Test'Class; Key : in String; Value : in String; Expect : in String) is H : constant String := Util.Encoders.HMAC.SHA1.Sign (Key, Value); begin Assert_Equals (T, Expect, Util.Strings.Transforms.To_Lower_Case (H), "Invalid HMAC-SHA1"); end Check_HMAC; -- ------------------------------ -- Test HMAC-SHA1 -- ------------------------------ procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test) is Key : constant String (1 .. 20) := (others => Character'Val (16#0b#)); begin Check_HMAC (T, Key, "Hi There", "b617318655057264e28bc0b6fb378c8ef146be00"); end Test_HMAC_SHA1_RFC2202_T1; procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test) is begin Check_HMAC (T, "Jefe", "what do ya want for nothing?", "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"); end Test_HMAC_SHA1_RFC2202_T2; procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test) is Key : constant String (1 .. 20) := (others => Character'Val (16#aa#)); Data : constant String (1 .. 50) := (others => Character'Val (16#dd#)); begin Check_HMAC (T, Key, Data, "125d7342b9ac11cd91a39af48aa17b4f63f175d3"); end Test_HMAC_SHA1_RFC2202_T3; procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test) is C : constant Util.Encoders.Encoder := Create ("hex"); Key : constant String := Util.Encoders.Decode (C, "0102030405060708090a0b0c0d0e0f" & "10111213141516171819"); Data : constant String (1 .. 50) := (others => Character'Val (16#cd#)); begin Check_HMAC (T, Key, Data, "4c9007f4026250c6bc8414f9bf50c86c2d7235da"); end Test_HMAC_SHA1_RFC2202_T4; procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test) is Key : constant String (1 .. 20) := (others => Character'Val (16#0c#)); begin -- RFC2202 test case 5 but without truncation... Check_HMAC (T, Key, "Test With Truncation", "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04"); end Test_HMAC_SHA1_RFC2202_T5; procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test) is Key : constant String (1 .. 80) := (others => Character'Val (16#aa#)); begin Check_HMAC (T, Key, "Test Using Larger Than Block-Size Key - Hash Key First", "aa4ae5e15272d00e95705637ce8a3b55ed402112"); end Test_HMAC_SHA1_RFC2202_T6; procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test) is Key : constant String (1 .. 80) := (others => Character'Val (16#Aa#)); begin Check_HMAC (T, Key, "Test Using Larger Than Block-Size Key and Larger " & "Than One Block-Size Data", "e8e99d0f45237d786d6bbaa7965c7808bbff1a91"); end Test_HMAC_SHA1_RFC2202_T7; end Util.Encoders.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
6a438bb72ff12657ad7dbbe5ed5eeae16347329c
src/os-linux/util-systems-os.ads
src/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type File_Type is new Integer; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Interfaces.C.int) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME); function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; pragma Import (C, Sys_Lseek, "lseek"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type File_Type is new Integer; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME); function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; pragma Import (C, Sys_Lseek, "lseek"); -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer; pragma Import (C, errno, "__get_errno"); end Util.Systems.Os;
Declare the Errno function
Declare the Errno function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b81926afe2487c7727aa777b7f2fdbaae28213cd
awa/regtests/awa-commands-tests.ads
awa/regtests/awa-commands-tests.ads
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test start and stop command. procedure Test_Start_Stop (T : in out Test); procedure Test_List_Tables (T : in out Test); -- Test the list -u command. procedure Test_List_Users (T : in out Test); -- Test the list -s command. procedure Test_List_Sessions (T : in out Test); -- Test the list -j command. procedure Test_List_Jobs (T : in out Test); -- Test the command with a secure keystore configuration. procedure Test_Secure_Configuration (T : in out Test); procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); end AWA.Commands.Tests;
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test start and stop command. procedure Test_Start_Stop (T : in out Test); procedure Test_List_Tables (T : in out Test); -- Test the list -u command. procedure Test_List_Users (T : in out Test); -- Test the list -s command. procedure Test_List_Sessions (T : in out Test); -- Test the list -j command. procedure Test_List_Jobs (T : in out Test); -- Test the command with a secure keystore configuration. procedure Test_Secure_Configuration (T : in out Test); -- Test the command with various logging options. procedure Test_Verbose_Command (T : in out Test); procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); end AWA.Commands.Tests;
Declare Test_Verbose_Command procedure
Declare Test_Verbose_Command procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
44231b3774deee8543d2fa1bf4a349bc949c7d71
jack-client.adb
jack-client.adb
with C_String.Arrays; with C_String; with Interfaces.C; package body Jack.Client is package C renames Interfaces.C; use type Thin.Status_t; use type System.Address; -- -- Activate -- procedure Activate (Client : in Client_t; Failed : out Boolean) is C_Return : constant C.int := Thin.Activate (System.Address (Client)); begin Failed := C_Return /= 0; end Activate; -- -- Get_Ports -- procedure Get_Ports_Free (Data : System.Address); pragma Import (C, Get_Ports_Free, "jack_ada_client_get_ports_free"); procedure Get_Ports (Client : in Client_t; Port_Name_Pattern : in String; Port_Type_Pattern : in String; Port_Flags : in Port_Flags_t; Ports : out Port_Name_Set_t) is Name : Port_Name_t; Size : Natural; C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags); C_Name : aliased C.char_array := C.To_C (Port_Name_Pattern); C_Type : aliased C.char_array := C.To_C (Port_Type_Pattern); Address : constant C_String.Arrays.Pointer_Array_t := Thin.Get_Ports (Client => System.Address (Client), Port_Name_Pattern => C_String.To_C_String (C_Name'Unchecked_Access), Type_Name_Pattern => C_String.To_C_String (C_Type'Unchecked_Access), Flags => C_Flags); begin Size := C_String.Arrays.Size_Terminated (Address); for Index in 0 .. Size loop Port_Names.Set_Bounded_String (Source => C_String.Arrays.Index_Terminated (Address, Index), Target => Name); Port_Name_Sets.Insert (Ports, Name); end loop; -- The strings returned by jack_get_ports are heap allocated. Get_Ports_Free (System.Address (Address)); end Get_Ports; -- -- Status, option and flag mapping. -- type Status_Map_t is array (Status_Selector_t) of Thin.Status_t; Status_Map : constant Status_Map_t := Status_Map_t' (Failure => Thin.JackFailure, Invalid_Option => Thin.JackInvalidOption, Name_Not_Unique => Thin.JackNameNotUnique, Server_Started => Thin.JackServerStarted, Server_Failed => Thin.JackServerFailed, Server_Error => Thin.JackServerError, No_Such_Client => Thin.JackNoSuchClient, Load_Failure => Thin.JackLoadFailure, Init_Failure => Thin.JackInitFailure, Shared_Memory_Failure => Thin.JackShmFailure, Version_Error => Thin.JackVersionError); type Options_Map_t is array (Option_Selector_t) of Thin.Options_t; Options_Map : constant Options_Map_t := Options_Map_t' (Do_Not_Start_Server => Thin.JackNoStartServer, Use_Exact_Name => Thin.JackUseExactName, Server_Name => Thin.JackServerName, Load_Name => Thin.JackLoadName, Load_Initialize => Thin.JackLoadInit); type Port_Flags_Map_t is array (Port_Flag_Selector_t) of Thin.Port_Flags_t; Port_Flags_Map : constant Port_Flags_Map_t := Port_Flags_Map_t' (Port_Is_Input => Thin.JackPortIsInput, Port_Is_Output => Thin.JackPortIsOutput, Port_Is_Physical => Thin.JackPortIsPhysical, Port_Can_Monitor => Thin.JackPortCanMonitor, Port_Is_Terminal => Thin.JackPortIsTerminal); function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t is Return_Options : Thin.Options_t := 0; begin for Selector in Options_t'Range loop if Options (Selector) then Return_Options := Return_Options or Options_Map (Selector); end if; end loop; return Return_Options; end Map_Options_To_Thin; function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t is Return_Port_Flags : Thin.Port_Flags_t := 0; begin for Selector in Port_Flags_t'Range loop if Port_Flags (Selector) then Return_Port_Flags := Return_Port_Flags or Port_Flags_Map (Selector); end if; end loop; return Return_Port_Flags; end Map_Port_Flags_To_Thin; function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t is Return_Status : Thin.Status_t := 0; begin for Selector in Status_t'Range loop if Status (Selector) then Return_Status := Return_Status or Status_Map (Selector); end if; end loop; return Return_Status; end Map_Status_To_Thin; function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t is Return_Options : Options_t := (others => False); begin for Selector in Options_t'Range loop Return_Options (Selector) := (Options and Options_Map (Selector)) = Options_Map (Selector); end loop; return Return_Options; end Map_Thin_To_Options; function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t is Return_Port_Flags : Port_Flags_t := (others => False); begin for Selector in Port_Flags_t'Range loop Return_Port_Flags (Selector) := (Port_Flags and Port_Flags_Map (Selector)) = Port_Flags_Map (Selector); end loop; return Return_Port_Flags; end Map_Thin_To_Port_Flags; function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t is Return_Status : Status_t := (others => False); begin for Selector in Status_t'Range loop Return_Status (Selector) := (Status and Status_Map (Selector)) = Status_Map (Selector); end loop; return Return_Status; end Map_Thin_To_Status; -- -- Open -- procedure Open (Client_Name : in String; Options : in Options_t; Client : out Client_t; Status : in out Status_t) is C_Options : constant Thin.Options_t := Map_Options_To_Thin (Options); C_Name : aliased C.char_array := C.To_C (Client_Name); C_Status : aliased Thin.Status_t; C_Client : System.Address; begin C_Client := Thin.Client_Open (Client_Name => C_String.To_C_String (C_Name'Unchecked_Access), Options => C_Options, Status => C_Status'Address); Status := Map_Thin_To_Status (C_Status); if C_Client = System.Null_Address then Client := Invalid_Client; else Client := Client_t (C_Client); end if; end Open; -- -- Port_Name_Size -- function Port_Name_Size return Natural is begin return Natural (Thin.Port_Name_Size); end Port_Name_Size; -- -- Port_Register -- procedure Port_Register (Client : in Client_t; Port : out Port_t; Port_Name : in Port_Name_t; Port_Type : in String; Port_Flags : in Port_Flags_t; Buffer_Size : in Natural := 0) is C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags); C_Name : aliased C.char_array := C.To_C (Port_Names.To_String (Port_Name)); C_Port : System.Address; C_Type : aliased C.char_array := C.To_C (Port_Type); begin C_Port := Thin.Port_Register (Client => System.Address (Client), Port_Name => C_String.To_C_String (C_Name'Unchecked_Access), Port_Type => C_String.To_C_String (C_Type'Unchecked_Access), Flags => C_Flags, Buffer_Size => C.unsigned_long (Buffer_Size)); if C_Port = System.Null_Address then Port := Invalid_Port; else Port := Port_t (C_Port); end if; end Port_Register; end Jack.Client;
with C_String.Arrays; with C_String; with Interfaces.C; package body Jack.Client is package C renames Interfaces.C; use type C.int; use type System.Address; use type Thin.Port_Flags_t; use type Thin.Status_t; -- -- Activate -- procedure Activate (Client : in Client_t; Failed : out Boolean) is C_Return : constant C.int := Thin.Activate (System.Address (Client)); begin Failed := C_Return /= 0; end Activate; -- -- Get_Ports -- procedure Get_Ports_Free (Data : System.Address); pragma Import (C, Get_Ports_Free, "jack_ada_client_get_ports_free"); procedure Get_Ports (Client : in Client_t; Port_Name_Pattern : in String; Port_Type_Pattern : in String; Port_Flags : in Port_Flags_t; Ports : out Port_Name_Set_t) is Name : Port_Name_t; Size : Natural; C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags); C_Name : aliased C.char_array := C.To_C (Port_Name_Pattern); C_Type : aliased C.char_array := C.To_C (Port_Type_Pattern); Address : constant C_String.Arrays.Pointer_Array_t := Thin.Get_Ports (Client => System.Address (Client), Port_Name_Pattern => C_String.To_C_String (C_Name'Unchecked_Access), Type_Name_Pattern => C_String.To_C_String (C_Type'Unchecked_Access), Flags => C_Flags); begin Size := C_String.Arrays.Size_Terminated (Address); for Index in 0 .. Size loop Port_Names.Set_Bounded_String (Source => C_String.Arrays.Index_Terminated (Address, Index), Target => Name); Port_Name_Sets.Insert (Ports, Name); end loop; -- The strings returned by jack_get_ports are heap allocated. Get_Ports_Free (System.Address (Address)); end Get_Ports; -- -- Status, option and flag mapping. -- type Status_Map_t is array (Status_Selector_t) of Thin.Status_t; Status_Map : constant Status_Map_t := Status_Map_t' (Failure => Thin.JackFailure, Invalid_Option => Thin.JackInvalidOption, Name_Not_Unique => Thin.JackNameNotUnique, Server_Started => Thin.JackServerStarted, Server_Failed => Thin.JackServerFailed, Server_Error => Thin.JackServerError, No_Such_Client => Thin.JackNoSuchClient, Load_Failure => Thin.JackLoadFailure, Init_Failure => Thin.JackInitFailure, Shared_Memory_Failure => Thin.JackShmFailure, Version_Error => Thin.JackVersionError); type Options_Map_t is array (Option_Selector_t) of Thin.Options_t; Options_Map : constant Options_Map_t := Options_Map_t' (Do_Not_Start_Server => Thin.JackNoStartServer, Use_Exact_Name => Thin.JackUseExactName, Server_Name => Thin.JackServerName, Load_Name => Thin.JackLoadName, Load_Initialize => Thin.JackLoadInit); type Port_Flags_Map_t is array (Port_Flag_Selector_t) of Thin.Port_Flags_t; Port_Flags_Map : constant Port_Flags_Map_t := Port_Flags_Map_t' (Port_Is_Input => Thin.JackPortIsInput, Port_Is_Output => Thin.JackPortIsOutput, Port_Is_Physical => Thin.JackPortIsPhysical, Port_Can_Monitor => Thin.JackPortCanMonitor, Port_Is_Terminal => Thin.JackPortIsTerminal); function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t is Return_Options : Thin.Options_t := 0; begin for Selector in Options_t'Range loop if Options (Selector) then Return_Options := Return_Options or Options_Map (Selector); end if; end loop; return Return_Options; end Map_Options_To_Thin; function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t is Return_Port_Flags : Thin.Port_Flags_t := 0; begin for Selector in Port_Flags_t'Range loop if Port_Flags (Selector) then Return_Port_Flags := Return_Port_Flags or Port_Flags_Map (Selector); end if; end loop; return Return_Port_Flags; end Map_Port_Flags_To_Thin; function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t is Return_Status : Thin.Status_t := 0; begin for Selector in Status_t'Range loop if Status (Selector) then Return_Status := Return_Status or Status_Map (Selector); end if; end loop; return Return_Status; end Map_Status_To_Thin; function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t is Return_Options : Options_t := (others => False); begin for Selector in Options_t'Range loop Return_Options (Selector) := (Options and Options_Map (Selector)) = Options_Map (Selector); end loop; return Return_Options; end Map_Thin_To_Options; function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t is Return_Port_Flags : Port_Flags_t := (others => False); begin for Selector in Port_Flags_t'Range loop Return_Port_Flags (Selector) := (Port_Flags and Port_Flags_Map (Selector)) = Port_Flags_Map (Selector); end loop; return Return_Port_Flags; end Map_Thin_To_Port_Flags; function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t is Return_Status : Status_t := (others => False); begin for Selector in Status_t'Range loop Return_Status (Selector) := (Status and Status_Map (Selector)) = Status_Map (Selector); end loop; return Return_Status; end Map_Thin_To_Status; -- -- Open -- procedure Open (Client_Name : in String; Options : in Options_t; Client : out Client_t; Status : in out Status_t) is C_Options : constant Thin.Options_t := Map_Options_To_Thin (Options); C_Name : aliased C.char_array := C.To_C (Client_Name); C_Status : aliased Thin.Status_t; C_Client : System.Address; begin C_Client := Thin.Client_Open (Client_Name => C_String.To_C_String (C_Name'Unchecked_Access), Options => C_Options, Status => C_Status'Address); Status := Map_Thin_To_Status (C_Status); if C_Client = System.Null_Address then Client := Invalid_Client; else Client := Client_t (C_Client); end if; end Open; -- -- Port_Name_Size -- function Port_Name_Size return Natural is begin return Natural (Thin.Port_Name_Size); end Port_Name_Size; -- -- Port_Register -- procedure Port_Register (Client : in Client_t; Port : out Port_t; Port_Name : in Port_Name_t; Port_Type : in String; Port_Flags : in Port_Flags_t; Buffer_Size : in Natural := 0) is C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags); C_Name : aliased C.char_array := C.To_C (Port_Names.To_String (Port_Name)); C_Port : System.Address; C_Type : aliased C.char_array := C.To_C (Port_Type); begin C_Port := Thin.Port_Register (Client => System.Address (Client), Port_Name => C_String.To_C_String (C_Name'Unchecked_Access), Port_Type => C_String.To_C_String (C_Type'Unchecked_Access), Flags => C_Flags, Buffer_Size => C.unsigned_long (Buffer_Size)); if C_Port = System.Null_Address then Port := Invalid_Port; else Port := Port_t (C_Port); end if; end Port_Register; end Jack.Client;
Use type declarations
Use type declarations
Ada
isc
io7m/coreland-jack-ada,io7m/coreland-jack-ada
e548294a4f666ee8b6a57235854c60e1eba06cf8
src/orka/interface/x86/generic/orka-transforms-simd_matrices.ads
src/orka/interface/x86/generic/orka-transforms-simd_matrices.ads
-- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.SIMD; generic type Element_Type is digits <>; type Vector_Type is array (SIMD.Index_Homogeneous) of Element_Type; type Matrix_Type is array (SIMD.Index_Homogeneous) of Vector_Type; with function Multiply_Matrices (Left, Right : Matrix_Type) return Matrix_Type; with function "-" (Elements : Vector_Type) return Vector_Type; with function Transpose_Matrix (Matrix : Matrix_Type) return Matrix_Type; package Orka.Transforms.SIMD_Matrices is pragma Preelaborate; subtype Matrix4 is Matrix_Type; subtype Vector4 is Vector_Type; function Identity_Value return Matrix_Type is (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 1.0))); function T (Offset : Vector_Type) return Matrix_Type; function Rx (Angle : Element_Type) return Matrix_Type; function Ry (Angle : Element_Type) return Matrix_Type; function Rz (Angle : Element_Type) return Matrix_Type; function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type; function S (Factors : Vector_Type) return Matrix_Type; function "*" (Left, Right : Matrix_Type) return Matrix_Type renames Multiply_Matrices; function "+" (Offset : Vector_Type; Matrix : Matrix_Type) return Matrix_Type; -- Add a translation transformation to the matrix function "*" (Factor : Element_Type; Matrix : Matrix_Type) return Matrix_Type; -- Add a scale transformation to the matrix procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Axis : Vector_Type; Angle : Element_Type); -- Add a rotation transformation to the matrix with the center -- of rotation at the origin to the matrix procedure Rotate (Matrix : in out Matrix_Type; Axis : Vector_Type; Angle : Element_Type; Point : Vector_Type); -- Add a rotation transformation to the matrix with the center -- of rotation at the given point to the matrix procedure Rotate_X_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type); -- Add a rotation transformation around the X axis with the center -- of rotation at the origin to the matrix procedure Rotate_Y_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type); -- Add a rotation transformation around the Y axis with the center -- of rotation at the origin to the matrix procedure Rotate_Z_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type); -- Add a rotation transformation around the Z axis with the center -- of rotation at the origin to the matrix procedure Rotate_X (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type); -- Add a rotation transformation around the X axis with the center -- of rotation at the given point to the matrix procedure Rotate_Y (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type); -- Add a rotation transformation around the Y axis with the center -- of rotation at the given point to the matrix procedure Rotate_Z (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type); -- Add a rotation transformation around the Z axis with the center -- of rotation at the given point to the matrix -- procedure Rotate_Quaternion (Matrix : in out Matrix_Type; Quaternion : ?); -- procedure Rotate_Euler (Matrix : in out Matrix_Type; Euler : ?); procedure Translate (Matrix : in out Matrix_Type; Offset : Vector_Type); -- Add a translation transformation to the matrix procedure Scale (Matrix : in out Matrix_Type; Factors : Vector_Type); procedure Scale (Matrix : in out Matrix_Type; Factor : Element_Type); procedure Transpose (Matrix : in out Matrix_Type); -- Transpose the matrix function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type; function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type; function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type; end Orka.Transforms.SIMD_Matrices;
-- 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 Orka.SIMD; generic type Element_Type is digits <>; type Vector_Type is array (SIMD.Index_Homogeneous) of Element_Type; type Matrix_Type is array (SIMD.Index_Homogeneous) of Vector_Type; with function Multiply_Matrices (Left, Right : Matrix_Type) return Matrix_Type; with function "-" (Elements : Vector_Type) return Vector_Type; with function Transpose_Matrix (Matrix : Matrix_Type) return Matrix_Type; package Orka.Transforms.SIMD_Matrices is pragma Preelaborate; subtype Matrix4 is Matrix_Type; subtype Vector4 is Vector_Type; function Identity_Value return Matrix_Type is (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 1.0))); function T (Offset : Vector_Type) return Matrix_Type; function Rx (Angle : Element_Type) return Matrix_Type; function Ry (Angle : Element_Type) return Matrix_Type; function Rz (Angle : Element_Type) return Matrix_Type; function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type; function S (Factors : Vector_Type) return Matrix_Type; function "*" (Left, Right : Matrix_Type) return Matrix_Type renames Multiply_Matrices; function "+" (Offset : Vector_Type; Matrix : Matrix_Type) return Matrix_Type; -- Add a translation transformation to the matrix function "*" (Factor : Element_Type; Matrix : Matrix_Type) return Matrix_Type; -- Add a scale transformation to the matrix procedure Rotate_At_Origin (Matrix : in out Matrix_Type; Axis : Vector_Type; Angle : Element_Type); -- Add a rotation transformation to the matrix with the center -- of rotation at the origin to the matrix procedure Rotate (Matrix : in out Matrix_Type; Axis : Vector_Type; Angle : Element_Type; Point : Vector_Type); -- Add a rotation transformation to the matrix with the center -- of rotation at the given point to the matrix procedure Rotate_X_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type); -- Add a rotation transformation around the X axis with the center -- of rotation at the origin to the matrix procedure Rotate_Y_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type); -- Add a rotation transformation around the Y axis with the center -- of rotation at the origin to the matrix procedure Rotate_Z_At_Origin (Matrix : in out Matrix_Type; Angle : Element_Type); -- Add a rotation transformation around the Z axis with the center -- of rotation at the origin to the matrix procedure Rotate_X (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type); -- Add a rotation transformation around the X axis with the center -- of rotation at the given point to the matrix procedure Rotate_Y (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type); -- Add a rotation transformation around the Y axis with the center -- of rotation at the given point to the matrix procedure Rotate_Z (Matrix : in out Matrix_Type; Angle : Element_Type; Point : Vector_Type); -- Add a rotation transformation around the Z axis with the center -- of rotation at the given point to the matrix -- procedure Rotate_Quaternion (Matrix : in out Matrix_Type; Quaternion : ?); -- procedure Rotate_Euler (Matrix : in out Matrix_Type; Euler : ?); procedure Translate (Matrix : in out Matrix_Type; Offset : Vector_Type); -- Add a translation transformation to the matrix procedure Scale (Matrix : in out Matrix_Type; Factors : Vector_Type); procedure Scale (Matrix : in out Matrix_Type; Factor : Element_Type); procedure Transpose (Matrix : in out Matrix_Type); -- Transpose the matrix function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0 and Z_Far > Z_Near; function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type with Pre => FOV > 0.0 and Aspect > 0.0 and Z_Near > 0.0; function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type with Pre => Z_Near >= 0.0 and Z_Far >= 0.0; end Orka.Transforms.SIMD_Matrices;
Add pre conditions to projection functions
orka: Add pre conditions to projection functions Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
dfb8a85459b173e86e307c7a30b01937794c291e
src/asf-validators-texts.adb
src/asf-validators-texts.adb
----------------------------------------------------------------------- -- asf-validators-texts -- ASF Texts Validators -- 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.Beans.Objects; -- The <b>ASF.Validators.Texts</b> defines various text oriented validators. package body ASF.Validators.Texts is -- ------------------------------ -- Length_Validator -- ------------------------------ -- ------------------------------ -- Create a length validator. -- ------------------------------ function Create_Length_Validator (Minimum : in Natural; Maximum : in Natural) return Validator_Access is Result : constant Length_Validator_Access := new Length_Validator; begin Result.Minimum := Minimum; Result.Maximum := Maximum; return Result.all'Access; end Create_Length_Validator; -- ------------------------------ -- Verify that the value's length is between the validator minimum and maximum -- boundaries. -- If some error are found, the procedure should create a <b>FacesMessage</b> -- describing the problem and add that message to the current faces context. -- The procedure can examine the state and modify the component tree. -- It must raise the <b>Invalid_Value</b> exception if the value is not valid. -- ------------------------------ procedure Validate (Valid : in Length_Validator; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Component : in out ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object) is begin if EL.Objects.Is_Null (Value) then return; end if; declare S : constant String := EL.Objects.To_String (Value); begin if S'Length > Valid.Maximum then Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME, Default => MAXIMUM_MESSAGE_ID, Arg1 => Util.Beans.Objects.To_Object (Valid.Maximum), Arg2 => Component.Get_Label (Context), Context => Context); raise Invalid_Value; end if; if S'Length < Valid.Minimum then Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME, Default => MINIMUM_MESSAGE_ID, Arg1 => Util.Beans.Objects.To_Object (Valid.Minimum), Arg2 => Component.Get_Label (Context), Context => Context); raise Invalid_Value; end if; end; end Validate; end ASF.Validators.Texts;
----------------------------------------------------------------------- -- asf-validators-texts -- ASF Texts Validators -- Copyright (C) 2011, 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.Beans.Objects; -- The <b>ASF.Validators.Texts</b> defines various text oriented validators. package body ASF.Validators.Texts is -- ------------------------------ -- Length_Validator -- ------------------------------ -- ------------------------------ -- Create a length validator. -- ------------------------------ function Create_Length_Validator (Minimum : in Natural; Maximum : in Natural) return Validator_Access is Result : constant Length_Validator_Access := new Length_Validator; begin Result.Minimum := Minimum; Result.Maximum := Maximum; return Result.all'Access; end Create_Length_Validator; -- ------------------------------ -- Verify that the value's length is between the validator minimum and maximum -- boundaries. -- If some error are found, the procedure should create a <b>FacesMessage</b> -- describing the problem and add that message to the current faces context. -- The procedure can examine the state and modify the component tree. -- It must raise the <b>Invalid_Value</b> exception if the value is not valid. -- ------------------------------ procedure Validate (Valid : in Length_Validator; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Component : in out ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object) is begin if EL.Objects.Is_Null (Value) then return; end if; declare S : constant String := EL.Objects.To_String (Value); begin if S'Length > Valid.Maximum then Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME, Default => MAXIMUM_MESSAGE_ID, Arg1 => Util.Beans.Objects.To_Object (Valid.Maximum), Arg2 => Component.Get_Label (Context), Context => Context); raise Invalid_Value; end if; if S'Length < Valid.Minimum then Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME, Default => MINIMUM_MESSAGE_ID, Arg1 => Util.Beans.Objects.To_Object (Valid.Minimum), Arg2 => Component.Get_Label (Context), Context => Context); raise Invalid_Value; end if; end; end Validate; -- ------------------------------ -- Regex_Validator -- ------------------------------ -- ------------------------------ -- Create a regex validator. -- ------------------------------ function Create_Regex_Validator (Pattern : in GNAT.Regpat.Pattern_Matcher) return Validator_Access is Result : constant Regex_Validator_Access := new Regex_Validator (Pattern.Size); begin Result.Pattern := Pattern; return Result.all'Access; end Create_Regex_Validator; -- ------------------------------ -- Verify that the value's length is between the validator minimum and maximum -- boundaries. -- If some error are found, the procedure should create a <b>FacesMessage</b> -- describing the problem and add that message to the current faces context. -- The procedure can examine the state and modify the component tree. -- It must raise the <b>Invalid_Value</b> exception if the value is not valid. -- ------------------------------ procedure Validate (Valid : in Regex_Validator; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Component : in out ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object) is begin if EL.Objects.Is_Null (Value) then return; end if; declare S : constant String := EL.Objects.To_String (Value); begin if not GNAT.Regpat.Match (Valid.Pattern, S) then Component.Add_Message (Name => ASF.Components.VALIDATOR_MESSAGE_NAME, Default => REGEX_MESSAGE_ID, Arg1 => Component.Get_Label (Context), Context => Context); raise Invalid_Value; end if; end; end Validate; end ASF.Validators.Texts;
Implement the Regex_Validator operation for the <f:validateRegex> JSF tag
Implement the Regex_Validator operation for the <f:validateRegex> JSF tag
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b2d368803008c221fb08a0418552bcb85eb92fb6
src/gen-model-operations.adb
src/gen-model-operations.adb
----------------------------------------------------------------------- -- gen-model-operations -- Operation 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. ----------------------------------------------------------------------- package body Gen.Model.Operations is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Operation_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "parameters" or Name = "columns" then return From.Parameters_Bean; elsif Name = "return" then return Util.Beans.Objects.To_Object (From.Return_Type); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Operation_Definition) is begin null; end Prepare; -- ------------------------------ -- Initialize the operation definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Operation_Definition) is begin O.Parameters_Bean := Util.Beans.Objects.To_Object (O.Parameters'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an operation parameter with the given name and type. -- ------------------------------ procedure Add_Parameter (Into : in out Operation_Definition; Name : in Unbounded_String; Of_Type : in Unbounded_String; Parameter : out Parameter_Definition_Access) is begin Parameter := new Parameter_Definition; Parameter.Name := Name; Parameter.Type_Name := Of_Type; Into.Parameters.Append (Parameter); end Add_Parameter; -- ------------------------------ -- Create an operation with the given name. -- ------------------------------ function Create_Operation (Name : in Unbounded_String) return Operation_Definition_Access is Result : constant Operation_Definition_Access := new Operation_Definition; begin return Result; end Create_Operation; end Gen.Model.Operations;
----------------------------------------------------------------------- -- gen-model-operations -- Operation 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. ----------------------------------------------------------------------- package body Gen.Model.Operations is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Operation_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "parameters" or Name = "columns" then return From.Parameters_Bean; elsif Name = "return" then return Util.Beans.Objects.To_Object (From.Return_Type); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Operation_Definition) is begin null; end Prepare; -- ------------------------------ -- Initialize the operation definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Operation_Definition) is begin O.Parameters_Bean := Util.Beans.Objects.To_Object (O.Parameters'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an operation parameter with the given name and type. -- ------------------------------ procedure Add_Parameter (Into : in out Operation_Definition; Name : in Unbounded_String; Of_Type : in Unbounded_String; Parameter : out Parameter_Definition_Access) is begin Parameter := new Parameter_Definition; Parameter.Name := Name; Parameter.Type_Name := Of_Type; Into.Parameters.Append (Parameter); end Add_Parameter; -- ------------------------------ -- Create an operation with the given name. -- ------------------------------ function Create_Operation (Name : in Unbounded_String) return Operation_Definition_Access is pragma Unreferenced (Name); Result : constant Operation_Definition_Access := new Operation_Definition; begin return Result; end Create_Operation; end Gen.Model.Operations;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
8b3992ccbb016eb41d91bf12729cf26cab918b80
awa/src/awa-permissions.adb
awa/src/awa-permissions.adb
----------------------------------------------------------------------- -- awa-permissions -- Permissions 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 Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Perm.Entity := Entity; if not Context.Has_Permission (Perm) then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and -- <entity-permission> XML entities are found. Create the new permission when the complete -- permission definition has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Entity = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entity => Into.Entity); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entity := 0; end; end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Entity_Policy) return String is begin return NAME; end Get_Name; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Perm.Entity := Entity; if not Context.Has_Permission (Perm) then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Objects.Object_Ref'Class) is begin if Entity.Is_Null then Log.Debug ("Permission is refused because the entity is null."); raise NO_PERMISSION; end if; Check (Permission, ADO.Objects.Get_Value (Entity.Get_Key)); end Check; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and -- <entity-permission> XML entities are found. Create the new permission when the complete -- permission definition has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Entity = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entity => Into.Entity); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entity := 0; end; end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Entity_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
Implement the Check procedure, if the database object is null, refuse the permission
Implement the Check procedure, if the database object is null, refuse the permission
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
4f351e6fb709df29bc0db031dcfb4b52b52ca7eb
regtests/util-processes-tests.ads
regtests/util-processes-tests.ads
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Processes.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Tests when the process is not launched procedure Test_No_Process (T : in out Test); -- Test executing a process procedure Test_Spawn (T : in out Test); -- Test output pipe redirection: read the process standard output procedure Test_Output_Pipe (T : in out Test); -- Test input pipe redirection: write the process standard input procedure Test_Input_Pipe (T : in out Test); -- Test shell splitting. procedure Test_Shell_Splitting_Pipe (T : in out Test); -- Test launching several processes through pipes in several threads. procedure Test_Multi_Spawn (T : in out Test); -- Test output file redirection. procedure Test_Output_Redirect (T : in out Test); -- Test input file redirection. procedure Test_Input_Redirect (T : in out Test); -- Test the Tools.Execute operation. procedure Test_Tools_Execute (T : in out Test); end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2016, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Processes.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Tests when the process is not launched procedure Test_No_Process (T : in out Test); -- Test executing a process procedure Test_Spawn (T : in out Test); -- Test output pipe redirection: read the process standard output procedure Test_Output_Pipe (T : in out Test); -- Test input pipe redirection: write the process standard input procedure Test_Input_Pipe (T : in out Test); -- Test shell splitting. procedure Test_Shell_Splitting_Pipe (T : in out Test); -- Test launching several processes through pipes in several threads. procedure Test_Multi_Spawn (T : in out Test); -- Test output file redirection. procedure Test_Output_Redirect (T : in out Test); -- Test input file redirection. procedure Test_Input_Redirect (T : in out Test); -- Test chaning working directory. procedure Test_Set_Working_Directory (T : in out Test); -- Test the Tools.Execute operation. procedure Test_Tools_Execute (T : in out Test); end Util.Processes.Tests;
Declare the Test_Set_Working_Directory procedure
Declare the Test_Set_Working_Directory procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9541f6ba92e6ea2dd1ffc4afcc699be9f06f3cee
src/asf-components-core-views.adb
src/asf-components-core-views.adb
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; package body ASF.Components.Core.Views is use ASF; use EL.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Components.Core.Views"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); end Encode_Begin; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is use type Base.UIComponent_Access; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; begin -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Begin (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- Clear the events that were queued. overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; package body ASF.Components.Core.Views is use ASF; use EL.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Components.Core.Views"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); end Encode_Begin; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is use type Base.UIComponent_Access; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; use type Base.UIComponent_Access; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then UIView'Class (Parent.all).Broadcast (Phase, Context); else -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end if; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Begin (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- Clear the events that were queued. overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
Fix broadcast phase events - propagate the broadcast to the parent component until the root is reached
Fix broadcast phase events - propagate the broadcast to the parent component until the root is reached
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6e7539921c9c00afc2272f818c4c1fbbe3b43147
src/security-oauth-clients.adb
src/security-oauth-clients.adb
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Properties.JSON; with Util.Encoders.HMAC.SHA1; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package body Security.OAuth.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); protected type Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array); private -- Random number generator used for ID generation. Random : Id_Random.Generator; -- Number of 32-bit random numbers used for the ID generation. Id_Size : Ada.Streams.Stream_Element_Offset := 8; end Random; protected body Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; use Interfaces; begin -- Generate the random sequence. for I in 0 .. Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Random); begin Into (4 * I) := Stream_Element (Value and 16#0FF#); Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; end Generate; end Random; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the id_token that was returned by the authentication process. -- ------------------------------ function Get_Id_Token (From : in OpenID_Token) return String is begin return From.Id_Token; end Get_Id_Token; -- ------------------------------ -- Get the application identifier. -- ------------------------------ function Get_Application_Identifier (App : in Application) return String is begin return Ada.Strings.Unbounded.To_String (App.Client_Id); end Get_Application_Identifier; -- ------------------------------ -- Set the application identifier used by the OAuth authorization server -- to identify the application (for example, the App ID in Facebook). -- ------------------------------ procedure Set_Application_Identifier (App : in out Application; Client : in String) is use Ada.Strings.Unbounded; begin App.Client_Id := To_Unbounded_String (Client); App.Protect := App.Client_Id & App.Callback; end Set_Application_Identifier; -- ------------------------------ -- Set the application secret defined in the OAuth authorization server -- for the application (for example, the App Secret in Facebook). -- ------------------------------ procedure Set_Application_Secret (App : in out Application; Secret : in String) is begin App.Secret := Ada.Strings.Unbounded.To_Unbounded_String (Secret); App.Key := App.Secret; end Set_Application_Secret; -- ------------------------------ -- Set the redirection callback that will be used to redirect the user -- back to the application after the OAuth authorization is finished. -- ------------------------------ procedure Set_Application_Callback (App : in out Application; URI : in String) is use Ada.Strings.Unbounded; begin App.Callback := To_Unbounded_String (URI); App.Protect := App.Client_Id & App.Callback; end Set_Application_Callback; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Protect); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Scope & "=" & Scope & "&" & Security.OAuth.State & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.Grant_Type & "=authorization_code" & "&" & Security.OAuth.Code & "=" & Code & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return null; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), "", "", Expires); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); return Application'Class (App).Create_Access_Token (P.Get ("access_token"), P.Get ("refresh_token", ""), P.Get ("id_token", ""), Expires); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin if Id_Token'Length > 0 then declare Result : constant OpenID_Token_Access := new OpenID_Token '(Len => Token'Length, Id_Len => Id_Token'Length, Refresh_Len => Refresh'Length, Access_Id => Token, Id_Token => Id_Token, Refresh_Token => Refresh); begin return Result.all'Access; end; else return new Access_Token '(Len => Token'Length, Access_Id => Token); end if; end Create_Access_Token; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Numerics.Discrete_Random; with Interfaces; with Ada.Streams; with Util.Log.Loggers; with Util.Strings; with Util.Http.Clients; with Util.Properties.JSON; with Util.Encoders.Base64; with Util.Encoders.HMAC.SHA1; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package body Security.OAuth.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients"); -- ------------------------------ -- Access Token -- ------------------------------ package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32); protected type Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array); private -- Random number generator used for ID generation. Random : Id_Random.Generator; end Random; protected body Random is procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; use Interfaces; Size : constant Ada.Streams.Stream_Element_Offset := Into'Last / 4; begin -- Generate the random sequence. for I in 0 .. Size loop declare Value : constant Unsigned_32 := Id_Random.Random (Random); begin Into (4 * I) := Stream_Element (Value and 16#0FF#); Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; end Generate; end Random; Random_Generator : Random; -- ------------------------------ -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. -- ------------------------------ function Create_Nonce (Bits : in Positive := 256) return String is use type Ada.Streams.Stream_Element_Offset; Rand_Count : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32)); Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1); Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3); Encoder : Util.Encoders.Base64.Encoder; Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; begin -- Generate the random sequence. Random_Generator.Generate (Rand); -- Encode the random stream in base64url and save it into the result string. Encoder.Set_URL_Mode (True); Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); declare Result : String (1 .. Natural (Encoded + 1)); begin for I in 0 .. Encoded loop Result (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; return Result; end; end Create_Nonce; -- ------------------------------ -- Get the principal name. This is the OAuth access token. -- ------------------------------ function Get_Name (From : in Access_Token) return String is begin return From.Access_Id; end Get_Name; -- ------------------------------ -- Get the id_token that was returned by the authentication process. -- ------------------------------ function Get_Id_Token (From : in OpenID_Token) return String is begin return From.Id_Token; end Get_Id_Token; -- ------------------------------ -- Get the application identifier. -- ------------------------------ function Get_Application_Identifier (App : in Application) return String is begin return Ada.Strings.Unbounded.To_String (App.Client_Id); end Get_Application_Identifier; -- ------------------------------ -- Set the application identifier used by the OAuth authorization server -- to identify the application (for example, the App ID in Facebook). -- ------------------------------ procedure Set_Application_Identifier (App : in out Application; Client : in String) is use Ada.Strings.Unbounded; begin App.Client_Id := To_Unbounded_String (Client); App.Protect := App.Client_Id & App.Callback; end Set_Application_Identifier; -- ------------------------------ -- Set the application secret defined in the OAuth authorization server -- for the application (for example, the App Secret in Facebook). -- ------------------------------ procedure Set_Application_Secret (App : in out Application; Secret : in String) is begin App.Secret := Ada.Strings.Unbounded.To_Unbounded_String (Secret); App.Key := App.Secret; end Set_Application_Secret; -- ------------------------------ -- Set the redirection callback that will be used to redirect the user -- back to the application after the OAuth authorization is finished. -- ------------------------------ procedure Set_Application_Callback (App : in out Application; URI : in String) is use Ada.Strings.Unbounded; begin App.Callback := To_Unbounded_String (URI); App.Protect := App.Client_Id & App.Callback; end Set_Application_Callback; -- ------------------------------ -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. -- ------------------------------ procedure Set_Provider_URI (App : in out Application; URI : in String) is begin App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI); end Set_Provider_URI; -- ------------------------------ -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. -- ------------------------------ function Get_State (App : in Application; Nonce : in String) return String is use Ada.Strings.Unbounded; Data : constant String := Nonce & To_String (App.Protect); Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Key), Data => Data, URL => True); begin -- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying... Hmac (Hmac'Last) := '.'; return Hmac; end Get_State; -- ------------------------------ -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. -- ------------------------------ function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String is begin return Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Scope & "=" & Scope & "&" & Security.OAuth.State & "=" & State; end Get_Auth_Params; -- ------------------------------ -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. -- ------------------------------ function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean is Hmac : constant String := Application'Class (App).Get_State (Nonce); begin return Hmac = State; end Is_Valid_State; -- ------------------------------ -- Exchange the OAuth code into an access token. -- ------------------------------ function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access is Client : Util.Http.Clients.Client; Response : Util.Http.Clients.Response; Data : constant String := Security.OAuth.Grant_Type & "=authorization_code" & "&" & Security.OAuth.Code & "=" & Code & "&" & Security.OAuth.Redirect_Uri & "=" & Ada.Strings.Unbounded.To_String (App.Callback) & "&" & Security.OAuth.Client_Id & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id) & "&" & Security.OAuth.Client_Secret & "=" & Ada.Strings.Unbounded.To_String (App.Secret); URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI); begin Log.Info ("Getting access token from {0}", URI); Client.Post (URL => URI, Data => Data, Reply => Response); if Response.Get_Status /= Util.Http.SC_OK then Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}", URI, Natural'Image (Response.Get_Status), Response.Get_Body); return null; end if; -- Decode the response. declare Content : constant String := Response.Get_Body; Content_Type : constant String := Response.Get_Header ("Content-Type"); Pos : Natural := Util.Strings.Index (Content_Type, ';'); Last : Natural; Expires : Natural; begin if Pos = 0 then Pos := Content_Type'Last; else Pos := Pos - 1; end if; Log.Debug ("Content type: {0}", Content_Type); Log.Debug ("Data: {0}", Content); -- Facebook sends the access token as a 'text/plain' content. if Content_Type (Content_Type'First .. Pos) = "text/plain" then Pos := Util.Strings.Index (Content, '='); if Pos = 0 then Log.Error ("Invalid access token response: '{0}'", Content); return null; end if; if Content (Content'First .. Pos) /= "access_token=" then Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content); return null; end if; Last := Util.Strings.Index (Content, '&', Pos + 1); if Last = 0 then Log.Error ("Invalid 'access_token' parameter: '{0}'", Content); return null; end if; if Content (Last .. Last + 8) /= "&expires=" then Log.Error ("Invalid 'expires' parameter: '{0}'", Content); return null; end if; Expires := Natural'Value (Content (Last + 9 .. Content'Last)); return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1), "", "", Expires); elsif Content_Type (Content_Type'First .. Pos) = "application/json" then declare P : Util.Properties.Manager; begin Util.Properties.JSON.Parse_JSON (P, Content); Expires := Natural'Value (P.Get ("expires_in")); return Application'Class (App).Create_Access_Token (P.Get ("access_token"), P.Get ("refresh_token", ""), P.Get ("id_token", ""), Expires); end; else Log.Error ("Content type {0} not supported for access token response", Content_Type); Log.Error ("Response: {0}", Content); return null; end if; end; end Request_Access_Token; -- ------------------------------ -- Create the access token -- ------------------------------ function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access is pragma Unreferenced (App, Expires); begin if Id_Token'Length > 0 then declare Result : constant OpenID_Token_Access := new OpenID_Token '(Len => Token'Length, Id_Len => Id_Token'Length, Refresh_Len => Refresh'Length, Access_Id => Token, Id_Token => Id_Token, Refresh_Token => Refresh); begin return Result.all'Access; end; else return new Access_Token '(Len => Token'Length, Access_Id => Token); end if; end Create_Access_Token; end Security.OAuth.Clients;
Implement the Create_Nonce by using a random generator and converting the result into base64url
Implement the Create_Nonce by using a random generator and converting the result into base64url
Ada
apache-2.0
stcarrez/ada-security
0baa7f4583515ec804c1df8c03d7bc784e30108a
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Filters.Html; with Wiki.Filters.TOC; with Wiki.Filters.Autolink; 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 = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; 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; -- ------------------------------ -- 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; Html : aliased Html_Writer_Type; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); 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); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_Wide_Wide_String (Value), Doc); Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Set_Render_TOC (UI.Get_Attribute (TOC_NAME, Context, False)); Renderer.Render (Doc); end if; Writer.End_Element ("div"); 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 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 : out Natural; Height : 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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.Filters.Html; with Wiki.Filters.TOC; with Wiki.Filters.Autolink; 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 = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; 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; -- ------------------------------ -- 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; Html : aliased Html_Writer_Type; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); 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); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Engine.Add_Filter (Autolink'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); Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Set_Render_TOC (UI.Get_Attribute (TOC_NAME, Context, False)); Renderer.Render (Doc); end if; Writer.End_Element ("div"); 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 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 : out Natural; Height : 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;
Use Util.Beans.Objects.To_String instead of Wide_Wide_String
Use Util.Beans.Objects.To_String instead of Wide_Wide_String
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
eb6c37a472e8c85f8623b49592bd8f90c1483cc0
regtests/util-encoders-tests.ads
regtests/util-encoders-tests.ads
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); end Util.Encoders.Tests;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in out Util.Encoders.Encoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); end Util.Encoders.Tests;
Declare new test procedures for HMAC-SHA256
Declare new test procedures for HMAC-SHA256
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
580fa7ac8260bf50d8272a7493f98650aeb79a73
regtests/util-encoders-tests.ads
regtests/util-encoders-tests.ads
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in Util.Encoders.Encoder; D : in Util.Encoders.Decoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_Encrypt_Decrypt_Secret (T : in out Test); -- Test Decode Quoted-Printable encoding. procedure Test_Decode_Quoted_Printable (T : in out Test); end Util.Encoders.Tests;
----------------------------------------------------------------------- -- util-encodes-tests - Test for encoding -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Encoders.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Hex (T : in out Test); procedure Test_Base64_Encode (T : in out Test); procedure Test_Base64_Decode (T : in out Test); procedure Test_Base64_URL_Encode (T : in out Test); procedure Test_Base64_URL_Decode (T : in out Test); procedure Test_Encoder (T : in out Test; C : in Util.Encoders.Encoder; D : in Util.Encoders.Decoder); procedure Test_Base64_Benchmark (T : in out Test); procedure Test_SHA1_Encode (T : in out Test); procedure Test_SHA256_Encode (T : in out Test); -- Benchmark test for SHA1 procedure Test_SHA1_Benchmark (T : in out Test); -- Test HMAC-SHA1 procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test); procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test); -- Test HMAC-SHA256 procedure Test_HMAC_SHA256_RFC4231_T1 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T2 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T3 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T4 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T5 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T6 (T : in out Test); procedure Test_HMAC_SHA256_RFC4231_T7 (T : in out Test); -- Test encoding leb128. procedure Test_LEB128 (T : in out Test); -- Test encoding leb128 + base64url. procedure Test_Base64_LEB128 (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_AES (T : in out Test); -- Test encrypt and decrypt operations. procedure Test_Encrypt_Decrypt_Secret (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_OFB (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_CFB (T : in out Test); procedure Test_Encrypt_Decrypt_Secret_CTR (T : in out Test); -- Test Decode Quoted-Printable encoding. procedure Test_Decode_Quoted_Printable (T : in out Test); end Util.Encoders.Tests;
Add Test_Encrypt_Decrypt_Secret_CTR/OFB/CFB to test other encryption modes
Add Test_Encrypt_Decrypt_Secret_CTR/OFB/CFB to test other encryption modes
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9dcdf2eca0c3c01ebf0c58e2284bbd22a6761fd1
mat/regtests/mat-targets-tests.adb
mat/regtests/mat-targets-tests.adb
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- 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.Directories; with Util.Test_Caller; with MAT.Readers.Files; package body MAT.Targets.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Targets.Read_File", Test_Read_File'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/file-v1.dat"); Target : MAT.Targets.Target_Type; Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Path); Reader.Read_All; end Test_Read_File; end MAT.Targets.Tests;
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- 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.Directories; with Util.Test_Caller; with MAT.Readers.Streams.Files; package body MAT.Targets.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Targets.Read_File", Test_Read_File'Access); end Add_Tests; -- ------------------------------ -- Test reading a file into a string -- Reads this ada source file and checks we have read it correctly -- ------------------------------ procedure Test_Read_File (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/file-v1.dat"); Target : MAT.Targets.Target_Type; Reader : MAT.Readers.Streams.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Path); Reader.Read_All; end Test_Read_File; end MAT.Targets.Tests;
Fix compilation of unit test
Fix compilation of unit test
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a5d7bf58a5e58ec430a35ccbfe675f2d9037c01d
mat/src/gtk/mat-targets-gtkmat.adb
mat/src/gtk/mat-targets-gtkmat.adb
----------------------------------------------------------------------- -- mat-targets-gtkmat - Gtk target management -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib.Error; with Gtk.Main; with MAT.Callbacks; package body MAT.Targets.Gtkmat is -- ------------------------------ -- Initialize the target instance. -- ------------------------------ overriding procedure Initialize (Target : in out Target_Type) is begin Target.Options.Graphical := True; end Initialize; -- ------------------------------ -- Initialize the widgets and create the Gtk gui. -- ------------------------------ procedure Initialize_Widget (Target : in out Target_Type; Widget : out Gtk.Widget.Gtk_Widget) is Error : aliased Glib.Error.GError; Result : Glib.Guint; begin if Target.Options.Graphical then Gtk.Main.Init; Gtkada.Builder.Gtk_New (Target.Builder); Result := Target.Builder.Add_From_File ("mat.glade", Error'Access); MAT.Callbacks.Initialize (Target.Builder); Target.Builder.Do_Connect; Widget := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main")); Widget.Show_All; Target.Gui_Task.Start (Widget); else Widget := null; end if; end Initialize_Widget; task body Gtk_Loop is Main : Gtk.Widget.Gtk_Widget; begin select accept Start (Widget : in Gtk.Widget.Gtk_Widget) do Main := Widget; end Start; Gtk.Main.Main; or terminate; end select; end Gtk_Loop; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ overriding procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is begin MAT.Targets.Target_Type (Target).Create_Process (Pid, Path, Process); end Create_Process; end MAT.Targets.Gtkmat;
----------------------------------------------------------------------- -- mat-targets-gtkmat - Gtk target management -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Glib.Error; with Gtk.Main; with MAT.Callbacks; package body MAT.Targets.Gtkmat is -- ------------------------------ -- Initialize the target instance. -- ------------------------------ overriding procedure Initialize (Target : in out Target_Type) is begin Target.Options.Interactive := False; Target.Options.Graphical := True; end Initialize; -- ------------------------------ -- Initialize the widgets and create the Gtk gui. -- ------------------------------ procedure Initialize_Widget (Target : in out Target_Type; Widget : out Gtk.Widget.Gtk_Widget) is Error : aliased Glib.Error.GError; Result : Glib.Guint; begin if Target.Options.Graphical then Gtk.Main.Init; Gtkada.Builder.Gtk_New (Target.Builder); Result := Target.Builder.Add_From_File ("mat.glade", Error'Access); MAT.Callbacks.Initialize (Target.Builder); Target.Builder.Do_Connect; Widget := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main")); else Widget := null; end if; end Initialize_Widget; -- ------------------------------ -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. -- ------------------------------ overriding procedure Interactive (Target : in out Target_Type) is Main : Gtk.Widget.Gtk_Widget; begin if Target.Options.Graphical then Main := Gtk.Widget.Gtk_Widget (Target.Builder.Get_Object ("main")); Main.Show_All; end if; if Target.Options.Interactive and Target.Options.Graphical then Target.Gui_Task.Start (Target'Unchecked_Access); end if; if Target.Options.Graphical then Gtk.Main.Main; else MAT.Targets.Target_Type (Target).Interactive; end if; end Interactive; task body Gtk_Loop is Main : Target_Type_Access; begin select accept Start (Target : in Target_Type_Access) do Main := Target; end Start; MAT.Targets.Target_Type (Main.all).Interactive; or terminate; end select; end Gtk_Loop; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ overriding procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is begin MAT.Targets.Target_Type (Target).Create_Process (Pid, Path, Process); end Create_Process; end MAT.Targets.Gtkmat;
Change to keep the Gtk thread on the main thread and have a specific task for the interactive mode when both interactive and graphical modes are enabled
Change to keep the Gtk thread on the main thread and have a specific task for the interactive mode when both interactive and graphical modes are enabled
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
eb9b77b9061db842ef1d86b5b1a942e69b6b7a6a
mat/src/mat-readers-marshaller.ads
mat/src/mat-readers-marshaller.ads
----------------------------------------------------------------------- -- Marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; -- Get a 32-bit value either from big-endian or little endian. function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; -- -- function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); -- -- function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); -- -- function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); -- -- function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; -- Get a 32-bit value either from big-endian or little endian. function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; -- Get a 64-bit value either from big-endian or little endian. function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; -- -- function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); -- -- function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); -- -- function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); -- -- function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
Document Get_Uint64
Document Get_Uint64
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f9d6d4163e07a44af7991ed75a9de8cca886cb80
src/security-openid-servlets.adb
src/security-openid-servlets.adb
----------------------------------------------------------------------- -- security-openid-servlets - Servlets for OpenID 2.0 Authentication -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with Util.Beans.Objects; with Util.Beans.Objects.Records; with Util.Log.Loggers; package body Security.Openid.Servlets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Openid.Servlets"); -- Make a package to store the Association in the session. package Association_Bean is new Util.Beans.Objects.Records (Security.Openid.Association); subtype Association_Access is Association_Bean.Element_Type_Access; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Openid_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- Property name that specifies the OpenID callback URL. OPENID_VERIFY_URL : constant String := "openid.callback_url"; -- Property name that specifies the realm. OPENID_REALM : constant String := "openid.realm"; -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; procedure Initialize (Server : in Openid_Servlet; Manager : in out Security.Openid.Manager) is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; Callback_URI : constant String := Ctx.Get_Init_Parameter (OPENID_VERIFY_URL); Realm : constant String := Ctx.Get_Init_Parameter (OPENID_REALM); begin Manager.Initialize (Return_To => Callback_URI, Name => Realm); end Initialize; function Get_Provider_URL (Server : in Request_Auth_Servlet; Request : in ASF.Requests.Request'Class) return String is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; URI : constant String := Request.Get_Path_Info; begin if URI'Length = 0 then return ""; end if; Log.Info ("OpenID authentication with {0}", URI); return Ctx.Get_Init_Parameter ("openid.provider." & URI (URI'First + 1 .. URI'Last)); end Get_Provider_URL; -- ------------------------------ -- Proceed to the OpenID authentication with an OpenID provider. -- Find the OpenID provider URL and starts the discovery, association phases -- during which a private key is obtained from the OpenID provider. -- After OpenID discovery and association, the user will be redirected to -- the OpenID provider. -- ------------------------------ procedure Do_Get (Server : in Request_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Provider : constant String := Server.Get_Provider_URL (Request); begin Log.Info ("Request OpenId authentication to {0}", Provider); if Provider'Length = 0 then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Mgr : Security.Openid.Manager; OP : Security.Openid.End_Point; Bean : constant Util.Beans.Objects.Object := Association_Bean.Create; Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean); begin Server.Initialize (Mgr); -- Yadis discovery (get the XRDS file). Mgr.Discover (Provider, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc.all); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Response.Send_Redirect (Location => Auth_URL); Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE, Value => Bean); end; end; end Do_Get; -- ------------------------------ -- Verify the authentication result that was returned by the OpenID provider. -- If the authentication succeeded and the signature was correct, sets a -- user principals on the session. -- ------------------------------ procedure Do_Get (Server : in Verify_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Session : ASF.Sessions.Session := Request.Get_Session (Create => False); Bean : constant Util.Beans.Objects.Object := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE); Mgr : Security.Openid.Manager; Assoc : Association_Access; Auth : Security.Openid.Authentication; Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; begin Log.Info ("Verify openid authentication"); -- Cleanup the session and drop the association end point. Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE); if Util.Beans.Objects.Is_Null (Bean) then Log.Warn ("Verify openid request without active session"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Assoc := Association_Bean.To_Element_Access (Bean); Server.Initialize (Mgr); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc.all, Request, Auth); if Get_Status (Auth) /= AUTHENTICATED then Log.Info ("Authentication has failed"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Log.Info ("Authentication succeeded for {0}", Get_Email (Auth)); -- Get a user principal and set it on the session. declare User : ASF.Principals.Principal_Access; URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url"); begin Verify_Auth_Servlet'Class (Server).Create_Principal (Auth, User); Session.Set_Principal (User); Log.Info ("Redirect user to success URL: {0}", URL); Response.Send_Redirect (Location => URL); end; end Do_Get; -- ------------------------------ -- Create a principal object that correspond to the authenticated user identified -- by the <b>Auth</b> information. The principal will be attached to the session -- and will be destroyed when the session is closed. -- ------------------------------ procedure Create_Principal (Server : in Verify_Auth_Servlet; Auth : in Authentication; Result : out ASF.Principals.Principal_Access) is pragma Unreferenced (Server); P : constant Principal_Access := new Principal; begin P.Auth := Auth; Result := P.all'Access; end Create_Principal; end Security.Openid.Servlets;
----------------------------------------------------------------------- -- security-openid-servlets - Servlets for OpenID 2.0 Authentication -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with Util.Beans.Objects; with Util.Beans.Objects.Records; with Util.Log.Loggers; package body Security.Openid.Servlets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Openid.Servlets"); -- Make a package to store the Association in the session. package Association_Bean is new Util.Beans.Objects.Records (Security.Openid.Association); subtype Association_Access is Association_Bean.Element_Type_Access; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Openid_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- Property name that specifies the OpenID callback URL. OPENID_VERIFY_URL : constant String := "openid.callback_url"; -- Property name that specifies the realm. OPENID_REALM : constant String := "openid.realm"; -- Name of the session attribute which holds information about the active authentication. OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc"; procedure Initialize (Server : in Openid_Servlet; Manager : in out Security.Openid.Manager) is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; Callback_URI : constant String := Ctx.Get_Init_Parameter (OPENID_VERIFY_URL); Realm : constant String := Ctx.Get_Init_Parameter (OPENID_REALM); begin Manager.Initialize (Return_To => Callback_URI, Name => Realm); end Initialize; function Get_Provider_URL (Server : in Request_Auth_Servlet; Request : in ASF.Requests.Request'Class) return String is Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; URI : constant String := Request.Get_Path_Info; begin if URI'Length = 0 then return ""; end if; Log.Info ("OpenID authentication with {0}", URI); return Ctx.Get_Init_Parameter ("openid.provider." & URI (URI'First + 1 .. URI'Last)); end Get_Provider_URL; -- ------------------------------ -- Proceed to the OpenID authentication with an OpenID provider. -- Find the OpenID provider URL and starts the discovery, association phases -- during which a private key is obtained from the OpenID provider. -- After OpenID discovery and association, the user will be redirected to -- the OpenID provider. -- ------------------------------ procedure Do_Get (Server : in Request_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Provider : constant String := Server.Get_Provider_URL (Request); begin Log.Info ("Request OpenId authentication to {0}", Provider); if Provider'Length = 0 then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Mgr : Security.Openid.Manager; OP : Security.Openid.End_Point; Bean : constant Util.Beans.Objects.Object := Association_Bean.Create; Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean); begin Server.Initialize (Mgr); -- Yadis discovery (get the XRDS file). Mgr.Discover (Provider, OP); -- Associate to the OpenID provider and get an end-point with a key. Mgr.Associate (OP, Assoc.all); -- Save the association in the HTTP session and -- redirect the user to the OpenID provider. declare Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Log.Info ("Redirect to auth URL: {0}", Auth_URL); Response.Send_Redirect (Location => Auth_URL); Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE, Value => Bean); end; end; end Do_Get; -- ------------------------------ -- Verify the authentication result that was returned by the OpenID provider. -- If the authentication succeeded and the signature was correct, sets a -- user principals on the session. -- ------------------------------ procedure Do_Get (Server : in Verify_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Session : ASF.Sessions.Session := Request.Get_Session (Create => False); Bean : Util.Beans.Objects.Object; Mgr : Security.Openid.Manager; Assoc : Association_Access; Auth : Security.Openid.Authentication; Ctx : constant ASF.Servlets.Servlet_Registry_Access := Server.Get_Servlet_Context; begin Log.Info ("Verify openid authentication"); if not Session.Is_Valid then Log.Warn ("Session has expired during OpenID authentication process"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE); -- Cleanup the session and drop the association end point. Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE); if Util.Beans.Objects.Is_Null (Bean) then Log.Warn ("Verify openid request without active session"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Assoc := Association_Bean.To_Element_Access (Bean); Server.Initialize (Mgr); -- Verify that what we receive through the callback matches the association key. Mgr.Verify (Assoc.all, Request, Auth); if Get_Status (Auth) /= AUTHENTICATED then Log.Info ("Authentication has failed"); Response.Set_Status (ASF.Responses.SC_FORBIDDEN); return; end if; Log.Info ("Authentication succeeded for {0}", Get_Email (Auth)); -- Get a user principal and set it on the session. declare User : ASF.Principals.Principal_Access; URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url"); begin Verify_Auth_Servlet'Class (Server).Create_Principal (Auth, User); Session.Set_Principal (User); Log.Info ("Redirect user to success URL: {0}", URL); Response.Send_Redirect (Location => URL); end; end Do_Get; -- ------------------------------ -- Create a principal object that correspond to the authenticated user identified -- by the <b>Auth</b> information. The principal will be attached to the session -- and will be destroyed when the session is closed. -- ------------------------------ procedure Create_Principal (Server : in Verify_Auth_Servlet; Auth : in Authentication; Result : out ASF.Principals.Principal_Access) is pragma Unreferenced (Server); P : constant Principal_Access := new Principal; begin P.Auth := Auth; Result := P.all'Access; end Create_Principal; end Security.Openid.Servlets;
Verify that the session is valid before getting the association attribute
Verify that the session is valid before getting the association attribute
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
8724079e54bdfba0b41396a114ebb0b9b911f1f6
src/core/strings/util-strings.adb
src/core/strings/util-strings.adb
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; package body Util.Strings is -- ------------------------------ -- Compute the hash value of the string. -- ------------------------------ function Hash (Key : Name_Access) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Key.all); end Hash; -- ------------------------------ -- Returns true if left and right strings are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : Name_Access) return Boolean is begin if Left = null or Right = null then return False; end if; return Left.all = Right.all; end Equivalent_Keys; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Integer) return String is S : constant String := Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Long_Long_Integer) return String is S : constant String := Long_Long_Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; use Util.Concurrent.Counters; -- ------------------------------ -- Create a string reference from a string. -- ------------------------------ function To_String_Ref (S : in String) return String_Ref is Str : constant String_Record_Access := new String_Record '(Len => S'Length, Str => S, Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Create a string reference from an unbounded string. -- ------------------------------ function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref is use Ada.Strings.Unbounded; Len : constant Natural := Length (S); Str : constant String_Record_Access := new String_Record '(Len => Len, Str => To_String (S), Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Get the string -- ------------------------------ function To_String (S : in String_Ref) return String is begin if S.Str = null then return ""; else return S.Str.Str; end if; end To_String; -- ------------------------------ -- Get the string as an unbounded string -- ------------------------------ function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String is begin if S.Str = null then return Ada.Strings.Unbounded.Null_Unbounded_String; else return Ada.Strings.Unbounded.To_Unbounded_String (S.Str.Str); end if; end To_Unbounded_String; -- ------------------------------ -- Compute the hash value of the string reference. -- ------------------------------ function Hash (Key : String_Ref) return Ada.Containers.Hash_Type is begin if Key.Str = null then return 0; else return Ada.Strings.Hash (Key.Str.Str); end if; end Hash; -- ------------------------------ -- Returns true if left and right string references are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : String_Ref) return Boolean is begin if Left.Str = Right.Str then return True; elsif Left.Str = null or Right.Str = null then return False; else return Left.Str.Str = Right.Str.Str; end if; end Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean is begin if Left.Str = null then return False; else return Left.Str.Str = Right; end if; end "="; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean is use Ada.Strings.Unbounded; begin if Left.Str = null then return Right = Null_Unbounded_String; else return Right = Left.Str.Str; end if; end "="; -- ------------------------------ -- Returns the string length. -- ------------------------------ function Length (S : in String_Ref) return Natural is begin if S.Str = null then return 0; else return S.Str.Len; end if; end Length; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out String_Ref) is begin if Object.Str /= null then Util.Concurrent.Counters.Increment (Object.Str.Counter); end if; end Adjust; -- ------------------------------ -- Decrement the reference counter and free the allocated string. -- ------------------------------ overriding procedure Finalize (Object : in out String_Ref) is procedure Free is new Ada.Unchecked_Deallocation (String_Record, String_Record_Access); Is_Zero : Boolean; begin if Object.Str /= null then Util.Concurrent.Counters.Decrement (Object.Str.Counter, Is_Zero); if Is_Zero then Free (Object.Str); else Object.Str := null; end if; end if; end Finalize; -- ------------------------------ -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'First; end if; for I in Pos .. Source'Last loop if Source (I) = Char then return I; end if; end loop; return 0; end Index; -- ------------------------------ -- Search for the first occurrence of the pattern in the string. -- ------------------------------ function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural is begin return Ada.Strings.Fixed.Index (Source, Pattern, From, Going); end Index; -- ------------------------------ -- Returns True if the source string starts with the given prefix. -- ------------------------------ function Starts_With (Source : in String; Prefix : in String) return Boolean is begin return Source'Length >= Prefix'Length and then Source (Source'First .. Source'First + Prefix'Length - 1) = Prefix; end Starts_With; -- ------------------------------ -- Returns True if the source string ends with the given suffix. -- ------------------------------ function Ends_With (Source : in String; Suffix : in String) return Boolean is begin return Source'Length >= Suffix'Length and then Source (Source'Last - Suffix'Length + 1 .. Source'Last) = Suffix; end Ends_With; -- ------------------------------ -- Returns True if the source contains the pattern. -- ------------------------------ function Contains (Source : in String; Pattern : in String) return Boolean is begin return Ada.Strings.Fixed.Index (Source, Pattern) /= 0; end Contains; -- ------------------------------ -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'Last; end if; for I in reverse Source'First .. Pos loop if Source (I) = Ch then return I; end if; end loop; return 0; end Rindex; end Util.Strings;
----------------------------------------------------------------------- -- util-strings -- Various String Utility -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017, 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.Fixed; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; package body Util.Strings is -- ------------------------------ -- Compute the hash value of the string. -- ------------------------------ function Hash (Key : Name_Access) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Key.all); end Hash; -- ------------------------------ -- Returns true if left and right strings are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : Name_Access) return Boolean is begin if Left = null or Right = null then return False; end if; return Left.all = Right.all; end Equivalent_Keys; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Integer) return String is S : constant String := Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- ------------------------------ -- Returns Integer'Image (Value) with the possible space stripped. -- ------------------------------ function Image (Value : in Long_Long_Integer) return String is S : constant String := Long_Long_Integer'Image (Value); begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; use Util.Concurrent.Counters; -- ------------------------------ -- Create a string reference from a string. -- ------------------------------ function To_String_Ref (S : in String) return String_Ref is Str : constant String_Record_Access := new String_Record '(Len => S'Length, Str => S, Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Create a string reference from an unbounded string. -- ------------------------------ function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref is use Ada.Strings.Unbounded; Len : constant Natural := Length (S); Str : constant String_Record_Access := new String_Record '(Len => Len, Str => To_String (S), Counter => ONE); begin return String_Ref '(Ada.Finalization.Controlled with Str => Str); end To_String_Ref; -- ------------------------------ -- Get the string -- ------------------------------ function To_String (S : in String_Ref) return String is begin if S.Str = null then return ""; else return S.Str.Str; end if; end To_String; -- ------------------------------ -- Get the string as an unbounded string -- ------------------------------ function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String is begin if S.Str = null then return Ada.Strings.Unbounded.Null_Unbounded_String; else return Ada.Strings.Unbounded.To_Unbounded_String (S.Str.Str); end if; end To_Unbounded_String; -- ------------------------------ -- Compute the hash value of the string reference. -- ------------------------------ function Hash (Key : String_Ref) return Ada.Containers.Hash_Type is begin if Key.Str = null then return 0; else return Ada.Strings.Hash (Key.Str.Str); end if; end Hash; -- ------------------------------ -- Returns true if left and right string references are equivalent. -- ------------------------------ function Equivalent_Keys (Left, Right : String_Ref) return Boolean is begin if Left.Str = Right.Str then return True; elsif Left.Str = null or Right.Str = null then return False; else return Left.Str.Str = Right.Str.Str; end if; end Equivalent_Keys; function "=" (Left : in String_Ref; Right : in String) return Boolean is begin if Left.Str = null then return False; else return Left.Str.Str = Right; end if; end "="; function "=" (Left : in String_Ref; Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean is use Ada.Strings.Unbounded; begin if Left.Str = null then return Right = Null_Unbounded_String; else return Right = Left.Str.Str; end if; end "="; -- ------------------------------ -- Returns the string length. -- ------------------------------ function Length (S : in String_Ref) return Natural is begin if S.Str = null then return 0; else return S.Str.Len; end if; end Length; -- ------------------------------ -- Increment the reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out String_Ref) is begin if Object.Str /= null then Util.Concurrent.Counters.Increment (Object.Str.Counter); end if; end Adjust; -- ------------------------------ -- Decrement the reference counter and free the allocated string. -- ------------------------------ overriding procedure Finalize (Object : in out String_Ref) is procedure Free is new Ada.Unchecked_Deallocation (String_Record, String_Record_Access); Is_Zero : Boolean; begin if Object.Str /= null then Util.Concurrent.Counters.Decrement (Object.Str.Counter, Is_Zero); if Is_Zero then Free (Object.Str); else Object.Str := null; end if; end if; end Finalize; -- ------------------------------ -- Search for the first occurrence of the character in the string -- after the from index. This implementation is 3-times faster than -- the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Index (Source : in String; Char : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'First; end if; for I in Pos .. Source'Last loop if Source (I) = Char then return I; end if; end loop; return 0; end Index; -- ------------------------------ -- Search for the first occurrence of the pattern in the string. -- ------------------------------ function Index (Source : in String; Pattern : in String; From : in Positive; Going : in Ada.Strings.Direction := Ada.Strings.Forward) return Natural is begin return Ada.Strings.Fixed.Index (Source, Pattern, From, Going); end Index; -- ------------------------------ -- Returns True if the source string starts with the given prefix. -- ------------------------------ function Starts_With (Source : in String; Prefix : in String) return Boolean is begin return Source'Length >= Prefix'Length and then Source (Source'First .. Source'First + Prefix'Length - 1) = Prefix; end Starts_With; -- ------------------------------ -- Returns True if the source string ends with the given suffix. -- ------------------------------ function Ends_With (Source : in String; Suffix : in String) return Boolean is begin return Source'Length >= Suffix'Length and then Source (Source'Last - Suffix'Length + 1 .. Source'Last) = Suffix; end Ends_With; -- ------------------------------ -- Returns True if the source contains the pattern. -- ------------------------------ function Contains (Source : in String; Pattern : in String) return Boolean is begin return Ada.Strings.Fixed.Index (Source, Pattern) /= 0; end Contains; -- ------------------------------ -- Search for the first occurrence of the character in the string -- before the from index and going backward. -- This implementation is 3-times faster than the Ada.Strings.Fixed version. -- Returns the index of the first occurrence or 0. -- ------------------------------ function Rindex (Source : in String; Ch : in Character; From : in Natural := 0) return Natural is Pos : Natural := From; begin if Pos < Source'First then Pos := Source'Last; end if; for I in reverse Source'First .. Pos loop if Source (I) = Ch then return I; end if; end loop; return 0; end Rindex; -- ------------------------------ -- Simple string replacement within the source of the specified content -- by another string. By default, replace only the first sequence. -- ------------------------------ function Replace (Source : in String; Content : in String; By : in String; First : in Boolean := True) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; Pos : Natural := Source'First; begin while Pos <= Source'Last loop if Source'Last - Pos >= Content'Length and then Source (Pos .. Pos + Content'Length - 1) = Content then Append (Result, By); Pos := Pos + Content'Length; if First and Pos <= Source'Last then Append (Result, Source (Pos .. Source'Last)); Pos := Source'Last + 1; end if; else Append (Result, Source (Pos)); Pos := Pos + 1; end if; end loop; return To_String (Result); end Replace; end Util.Strings;
Implement the Replace function
Implement the Replace function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f5604b275b2ccc33217f82264c65cd500cb3b7d1
src/util-nullables.ads
src/util-nullables.ads
----------------------------------------------------------------------- -- util-nullables -- Basic types that can hold a null value -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; -- === Nullable types === -- Sometimes it is necessary to represent a simple data type with an optional boolean information -- that indicates whether the value is valid or just null. The concept of nullable type is often -- used in databases but also in JSON data representation. The <tt>Util.Nullables</tt> package -- provides several standard type to express the null capability of a value. -- -- By default a nullable instance is created with the null flag set. package Util.Nullables is use type Ada.Strings.Unbounded.Unbounded_String; use type Ada.Calendar.Time; -- ------------------------------ -- A boolean which can be null. -- ------------------------------ type Nullable_Boolean is record Value : Boolean := False; Is_Null : Boolean := True; end record; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Boolean) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- An integer which can be null. -- ------------------------------ type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Integer) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A long which can be null. -- ------------------------------ type Nullable_Long is record Value : Long_Long_Integer := 0; Is_Null : Boolean := True; end record; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Long) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A string which can be null. -- ------------------------------ type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_String) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A date which can be null. -- ------------------------------ type Nullable_Time is record Value : Ada.Calendar.Time; Is_Null : Boolean := True; end record; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); end Util.Nullables;
----------------------------------------------------------------------- -- util-nullables -- Basic types that can hold a null value -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; -- === Nullable types === -- Sometimes it is necessary to represent a simple data type with an optional boolean information -- that indicates whether the value is valid or just null. The concept of nullable type is often -- used in databases but also in JSON data representation. The <tt>Util.Nullables</tt> package -- provides several standard type to express the null capability of a value. -- -- By default a nullable instance is created with the null flag set. package Util.Nullables is use type Ada.Strings.Unbounded.Unbounded_String; use type Ada.Calendar.Time; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- A boolean which can be null. -- ------------------------------ type Nullable_Boolean is record Value : Boolean := False; Is_Null : Boolean := True; end record; Null_Boolean : constant Nullable_Boolean; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Boolean) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- An integer which can be null. -- ------------------------------ type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; Null_Integer : constant Nullable_Integer; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Integer) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A long which can be null. -- ------------------------------ type Nullable_Long is record Value : Long_Long_Integer := 0; Is_Null : Boolean := True; end record; Null_Long : constant Nullable_Long; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Long) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A string which can be null. -- ------------------------------ type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; Null_String : constant Nullable_String; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_String) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A date which can be null. -- ------------------------------ type Nullable_Time is record Value : Ada.Calendar.Time := DEFAULT_TIME; Is_Null : Boolean := True; end record; Null_Time : constant Nullable_Time; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); Null_Boolean : constant Nullable_Boolean := Nullable_Boolean '(Is_Null => True, Value => False); Null_Integer : constant Nullable_Integer := Nullable_Integer '(Is_Null => True, Value => 0); Null_Long : constant Nullable_Long := Nullable_Long '(Is_Null => True, Value => 0); Null_String : constant Nullable_String := Nullable_String '(Is_Null => True, Value => Ada.Strings.Unbounded.Null_Unbounded_String); Null_Time : constant Nullable_Time := Nullable_Time '(Is_Null => True, Value => DEFAULT_TIME); end Util.Nullables;
Declare DEFAULT_TIME, Null_Integer, Null_Boolean, Null_String, Null_Time constants
Declare DEFAULT_TIME, Null_Integer, Null_Boolean, Null_String, Null_Time constants
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
752c63e645748b9f829841f89d93e526a354839e
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Blogs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record Blog_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Uri : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the blog as anonymous users. procedure Verify_Anonymous (T : in out Test; Post : in String); -- Test access to the blog as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of blog by simulating web requests. procedure Test_Create_Blog (T : in out Test); -- Test updating a post by simulating web requests. procedure Test_Update_Post (T : in out Test); end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Blogs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record Blog_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Uri : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the blog as anonymous users. procedure Verify_Anonymous (T : in out Test; Post : in String); -- Test access to the blog as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of blog by simulating web requests. procedure Test_Create_Blog (T : in out Test); -- Test updating a post by simulating web requests. procedure Test_Update_Post (T : in out Test); -- Test listing the blog posts. procedure Test_Admin_List_Posts (T : in out Test); end AWA.Blogs.Tests;
Declare the Test_Admin_List_Posts procedure for another unit test
Declare the Test_Admin_List_Posts procedure for another unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
abdf86ab6c426d51017060d55b71236d9aba30f1
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Blogs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record Blog_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Uri : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the blog as anonymous users. procedure Verify_Anonymous (T : in out Test; Post : in String); -- Test access to the blog as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of blog by simulating web requests. procedure Test_Create_Blog (T : in out Test); -- Test updating a post by simulating web requests. procedure Test_Update_Post (T : in out Test); -- Test listing the blog posts. procedure Test_Admin_List_Posts (T : in out Test); end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Blogs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record Blog_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Uri : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the blog as anonymous users. procedure Verify_Anonymous (T : in out Test; Post : in String); -- Test access to the blog as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of blog by simulating web requests. procedure Test_Create_Blog (T : in out Test); -- Test updating a post by simulating web requests. procedure Test_Update_Post (T : in out Test); -- Test listing the blog posts. procedure Test_Admin_List_Posts (T : in out Test); -- Test listing the blog comments. procedure Test_Admin_List_Comments (T : in out Test); end AWA.Blogs.Tests;
Declare the Test_Admin_List_Comments procedure to test the list of comments
Declare the Test_Admin_List_Comments procedure to test the list of comments
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d4f0c4a3c041ae7577045f60275d19bd02c28eb3
mat/src/events/mat-events-targets.ads
mat/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the first and last event that have been received. procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is (MSG_BEGIN, MSG_END, MSG_LIBRARY, MSG_MALLOC, MSG_FREE, MSG_REALLOC ); type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the first and last event that have been received. procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
Change the Probe_Index_Type to an enum with the declaration of all supported message types
Change the Probe_Index_Type to an enum with the declaration of all supported message types
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fd99bb94b5be6a3e41eb38f6f4aed043722e1228
awa/src/awa-modules-lifecycles.adb
awa/src/awa-modules-lifecycles.adb
----------------------------------------------------------------------- -- awa-modules-lifecycles -- Lifecycle listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Modules.Lifecycles is -- ------------------------------ -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). -- ------------------------------ procedure Notify_Create (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type) is begin LF.Notify_Create (Service.Module.Listeners, Item); end Notify_Create; -- ------------------------------ -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). -- ------------------------------ procedure Notify_Update (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type) is begin LF.Notify_Update (Service.Module.Listeners, Item); end Notify_Update; -- ------------------------------ -- Inform the the lifecycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). -- ------------------------------ procedure Notify_Delete (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type) is begin LF.Notify_Delete (Service.Module.Listeners, Item); end Notify_Delete; end AWA.Modules.Lifecycles;
----------------------------------------------------------------------- -- awa-modules-lifecycles -- Lifecycle listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Modules.Lifecycles is -- ------------------------------ -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). -- ------------------------------ procedure Notify_Create (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type) is begin LF.Notify_Create (Service.Module.Listeners, Item); end Notify_Create; -- ------------------------------ -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been created (calls `On_Create`). -- ------------------------------ procedure Notify_Create (Service : in AWA.Modules.Module'Class; Item : in Element_Type) is begin LF.Notify_Create (Service.Listeners, Item); end Notify_Create; -- ------------------------------ -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). -- ------------------------------ procedure Notify_Update (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type) is begin LF.Notify_Update (Service.Module.Listeners, Item); end Notify_Update; -- ------------------------------ -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been updated (calls `On_Update`). -- ------------------------------ procedure Notify_Update (Service : in AWA.Modules.Module'Class; Item : in Element_Type) is begin LF.Notify_Update (Service.Listeners, Item); end Notify_Update; -- ------------------------------ -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). -- ------------------------------ procedure Notify_Delete (Service : in AWA.Modules.Module_Manager'Class; Item : in Element_Type) is begin LF.Notify_Delete (Service.Module.Listeners, Item); end Notify_Delete; -- ------------------------------ -- Inform the the life cycle listeners registered in `List` that the item passed in `Item` -- has been deleted (calls `On_Delete`). -- ------------------------------ procedure Notify_Delete (Service : in AWA.Modules.Module'Class; Item : in Element_Type) is begin LF.Notify_Delete (Service.Listeners, Item); end Notify_Delete; end AWA.Modules.Lifecycles;
Implement the Notify_Create, Notify_Update and Notify_Delete with the Module'Class instance
Implement the Notify_Create, Notify_Update and Notify_Delete with the Module'Class instance
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
ca4045b5e69ccfa0a0a8bfbb17f16bc9fa4a2f6b
src/asf-components-html-lists.adb
src/asf-components-html-lists.adb
----------------------------------------------------------------------- -- html.lists -- List of items -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Basic; with ASF.Components.Base; package body ASF.Components.Html.Lists is use Util.Log; use type EL.Objects.Data_Type; Log : constant Loggers.Logger := Loggers.Create ("ASF.Components.Html.Lists"); -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ function Get_Value (UI : in UIList) return EL.Objects.Object is begin return UI.Get_Attribute (UI.Get_Context.all, "value"); end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ procedure Set_Value (UI : in out UIList; Value : in EL.Objects.Object) is begin null; end Set_Value; -- ------------------------------ -- Get the variable name -- ------------------------------ function Get_Var (UI : in UIList) return String is Var : constant EL.Objects.Object := UI.Get_Attribute (UI.Get_Context.all, "var"); begin return EL.Objects.To_String (Var); end Get_Var; procedure Encode_Children (UI : in UIList; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Value : EL.Objects.Object := Get_Value (UI); Kind : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value); Name : constant String := UI.Get_Var; Bean : access Util.Beans.Basic.Readonly_Bean'Class; Is_Reverse : constant Boolean := UI.Get_Attribute ("reverse", Context, False); List : Util.Beans.Basic.List_Bean_Access; Count : Natural; begin -- Check that we have a List_Bean but do not complain if we have a null value. if Kind /= EL.Objects.TYPE_BEAN then if Kind /= EL.Objects.TYPE_NULL then Log.Error ("Invalid list bean (found a {0})", EL.Objects.Get_Type_Name (Value)); end if; return; end if; Bean := EL.Objects.To_Bean (Value); if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then Log.Error ("Invalid list bean: it does not implement 'List_Bean' interface"); return; end if; List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access; Count := List.Get_Count; if Is_Reverse then for I in reverse 1 .. Count loop List.Set_Row_Index (I); Value := List.Get_Row; Context.Set_Attribute (Name, Value); Log.Debug ("Set variable {0}", Name); Base.UIComponent (UI).Encode_Children (Context); end loop; else for I in 1 .. Count loop List.Set_Row_Index (I); Value := List.Get_Row; Context.Set_Attribute (Name, Value); Log.Debug ("Set variable {0}", Name); Base.UIComponent (UI).Encode_Children (Context); end loop; end if; end; end Encode_Children; end ASF.Components.Html.Lists;
----------------------------------------------------------------------- -- html.lists -- List of items -- Copyright (C) 2009, 2010, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Basic; with ASF.Components.Base; package body ASF.Components.Html.Lists is use Util.Log; use type EL.Objects.Data_Type; Log : constant Loggers.Logger := Loggers.Create ("ASF.Components.Html.Lists"); -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ function Get_Value (UI : in UIList) return EL.Objects.Object is begin return UI.Get_Attribute (UI.Get_Context.all, "value"); end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ procedure Set_Value (UI : in out UIList; Value : in EL.Objects.Object) is begin null; end Set_Value; -- ------------------------------ -- Get the variable name -- ------------------------------ function Get_Var (UI : in UIList) return String is Var : constant EL.Objects.Object := UI.Get_Attribute (UI.Get_Context.all, "var"); begin return EL.Objects.To_String (Var); end Get_Var; procedure Encode_Children (UI : in UIList; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Value : EL.Objects.Object := Get_Value (UI); Kind : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value); Name : constant String := UI.Get_Var; Bean : access Util.Beans.Basic.Readonly_Bean'Class; Is_Reverse : constant Boolean := UI.Get_Attribute ("reverse", Context, False); List : Util.Beans.Basic.List_Bean_Access; Count : Natural; begin -- Check that we have a List_Bean but do not complain if we have a null value. if Kind /= EL.Objects.TYPE_BEAN then if Kind /= EL.Objects.TYPE_NULL then ASF.Components.Base.Log_Error (UI, "Invalid list bean (found a {0})", EL.Objects.Get_Type_Name (Value)); end if; return; end if; Bean := EL.Objects.To_Bean (Value); if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then ASF.Components.Base.Log_Error (UI, "Invalid list bean: " & "it does not implement 'List_Bean' interface"); return; end if; List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access; Count := List.Get_Count; if Is_Reverse then for I in reverse 1 .. Count loop List.Set_Row_Index (I); Value := List.Get_Row; Context.Set_Attribute (Name, Value); Log.Debug ("Set variable {0}", Name); Base.UIComponent (UI).Encode_Children (Context); end loop; else for I in 1 .. Count loop List.Set_Row_Index (I); Value := List.Get_Row; Context.Set_Attribute (Name, Value); Log.Debug ("Set variable {0}", Name); Base.UIComponent (UI).Encode_Children (Context); end loop; end if; end; end Encode_Children; end ASF.Components.Html.Lists;
Use the Log_Error procedure to report the error message and associate the error with the view file and line number
Use the Log_Error procedure to report the error message and associate the error with the view file and line number
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6b2d38a373ce048c4e94b54160e521202604d508
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Objects.To_Object (From.Get_Folder.Get_Key); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; begin if Name = "folderId" then Manager.Load_Folder (Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Bean.Set_Name (Part.Get_Name); Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- @method -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with ADO; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Objects.To_Object (From.Get_Folder.Get_Key); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; begin if Name = "folderId" then Manager.Load_Folder (Folder, ADO.Utils.To_Identifier (Value)); From.Set_Folder (Folder); elsif Name = "id" then Manager.Load_Storage (From, ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Bean.Set_Name (Part.Get_Name); Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- @method -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (0).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Storage.Module.Get_Session; Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Storages.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
Use the ADO.Utils.To_Identifier operation
Use the ADO.Utils.To_Identifier operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
121fbdfa8dff3cb0bd7968978e94b58a6eb3daaa
src/sqlite/ado-schemas-sqlite.adb
src/sqlite/ado-schemas-sqlite.adb
----------------------------------------------------------------------- -- ado-schemas -- Database Schemas -- Copyright (C) 2015, 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 ADO.Statements; with ADO.Statements.Create; with Ada.Strings.Fixed; with Util.Strings.Transforms; package body ADO.Schemas.Sqlite is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Length (Value : in String) return Natural; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int" or Value = "integer" then return T_INTEGER; elsif Value = "bigint" then return T_LONG_INTEGER; elsif Value = "tinyint" then return T_TINYINT; elsif Value = "smallint" then return T_SMALLINT; elsif Value = "blob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "real" or Name = "float" or Name = "double" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; function String_To_Length (Value : in String) return Natural is First : Natural; Last : Natural; begin First := Ada.Strings.Fixed.Index (Value, "("); if First = 0 then return 0; end if; Last := Ada.Strings.Fixed.Index (Value, ")"); if Last < First then return 0; end if; return Natural'Value (Value (First + 1 .. Last - 1)); exception when Constraint_Error => return 0; end String_To_Length; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("pragma table_info('" & Name & "')")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; begin Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (1); Col.Collation := Stmt.Get_Unbounded_String (2); Col.Default := Stmt.Get_Unbounded_String (5); if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (2); declare Type_Name : constant String := Util.Strings.Transforms.To_Lower_Case (To_String (Value)); begin Col.Col_Type := String_To_Type (Type_Name); Col.Size := String_To_Length (Type_Name); end; Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "0"; Value := Stmt.Get_Unbounded_String (5); Col.Is_Primary := Value = "1"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("SELECT NAME FROM sqlite_master")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop declare Name : constant String := Stmt.Get_String (0); begin if not Util.Strings.Starts_With (Name, "sqlite_") then Table := new ADO.Schemas.Table; Table.Name := To_Unbounded_String (Name); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; end if; end; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Sqlite;
----------------------------------------------------------------------- -- ado-schemas -- Database Schemas -- Copyright (C) 2015, 2018, 2019, 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 ADO.Statements; with ADO.Statements.Create; with Ada.Strings.Fixed; with Util.Strings.Transforms; package body ADO.Schemas.Sqlite is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Length (Value : in String) return Natural; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int" or Value = "integer" then return T_INTEGER; elsif Value = "bigint" then return T_LONG_INTEGER; elsif Value = "tinyint" then return T_TINYINT; elsif Value = "smallint" then return T_SMALLINT; elsif Value = "float" then return T_FLOAT; elsif Value = "double" then return T_DOUBLE; elsif Value = "blob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "real" or Name = "float" or Name = "double" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; function String_To_Length (Value : in String) return Natural is First : Natural; Last : Natural; begin First := Ada.Strings.Fixed.Index (Value, "("); if First = 0 then return 0; end if; Last := Ada.Strings.Fixed.Index (Value, ")"); if Last < First then return 0; end if; return Natural'Value (Value (First + 1 .. Last - 1)); exception when Constraint_Error => return 0; end String_To_Length; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("pragma table_info('" & Name & "')")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; begin Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (1); if not Stmt.Is_Null (4) then Col.Default := Stmt.Get_Unbounded_String (4); end if; if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (2); declare Type_Name : constant String := Util.Strings.Transforms.To_Lower_Case (To_String (Value)); begin Col.Col_Type := String_To_Type (Type_Name); Col.Size := String_To_Length (Type_Name); end; Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "0"; Value := Stmt.Get_Unbounded_String (5); Col.Is_Primary := Value = "1"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("SELECT NAME FROM sqlite_master")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop declare Name : constant String := Stmt.Get_String (0); begin if not Util.Strings.Starts_With (Name, "sqlite_") then Table := new ADO.Schemas.Table; Table.Name := To_Unbounded_String (Name); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; end if; end; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Sqlite;
Fix support for Float and Double in SQLite schema loading Fix getting the default column value
Fix support for Float and Double in SQLite schema loading Fix getting the default column value
Ada
apache-2.0
stcarrez/ada-ado
cd94e4d348a4bcdb26e7915f2845f1bb1975e5fc
src/asf-components-widgets-tabs.adb
src/asf-components-widgets-tabs.adb
----------------------------------------------------------------------- -- components-widgets-tabs -- Tab views and tabs -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Tabs is -- ------------------------------ -- Render the tab start. -- ------------------------------ overriding procedure Encode_Begin (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("id", UI.Get_Client_Id); end if; end Encode_Begin; -- ------------------------------ -- Render the tab close. -- ------------------------------ overriding procedure Encode_End (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); end if; end Encode_End; -- ------------------------------ -- Render the tab list and prepare to render the tab contents. -- ------------------------------ overriding procedure Encode_Begin (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Render_Tab (T : in Components.Base.UIComponent_Access); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; procedure Render_Tab (T : in Components.Base.UIComponent_Access) is Id : constant Unbounded_String := T.Get_Client_Id; begin if T.all in UITab'Class then Writer.Start_Element ("li"); Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "#" & To_String (Id)); Writer.Write_Text (T.Get_Attribute ("title", Context)); Writer.End_Element ("a"); Writer.End_Element ("li"); end if; end Render_Tab; procedure Render_Tabs is new ASF.Components.Base.Iterate (Process => Render_Tab); begin if UI.Is_Rendered (Context) then declare use Util.Beans.Objects; Id : constant Unbounded_String := UI.Get_Client_Id; Effect : constant Object := UI.Get_Attribute (Context, Name => EFFECT_ATTR_NAME); Collapse : constant Boolean := UI.Get_Attribute (COLLAPSIBLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("id", Id); Writer.Start_Element ("ul"); Render_Tabs (UI); Writer.End_Element ("ul"); Writer.Queue_Script ("$(""#"); Writer.Queue_Script (Id); Writer.Queue_Script (""").tabs({"); if Collapse then Writer.Queue_Script ("collapsible: true"); end if; if not Is_Empty (Effect) then if Collapse then Writer.Queue_Script (","); end if; Writer.Queue_Script ("show:{effect:"""); Writer.Queue_Script (Effect); Writer.Queue_Script (""",duration:"); Writer.Queue_Script (UI.Get_Attribute (DURATION_ATTR_NAME, Context, "500")); Writer.Queue_Script ("}"); end if; Writer.Queue_Script ("});"); end; end if; end Encode_Begin; -- ------------------------------ -- Render the tab view close. -- ------------------------------ overriding procedure Encode_End (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Tabs;
----------------------------------------------------------------------- -- components-widgets-tabs -- Tab views and tabs -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Tabs is -- ------------------------------ -- Render the tab start. -- ------------------------------ overriding procedure Encode_Begin (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("id", UI.Get_Client_Id); end if; end Encode_Begin; -- ------------------------------ -- Render the tab close. -- ------------------------------ overriding procedure Encode_End (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); end if; end Encode_End; -- ------------------------------ -- Render the tab list and prepare to render the tab contents. -- ------------------------------ overriding procedure Encode_Begin (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Render_Tab (T : in Components.Base.UIComponent_Access); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; procedure Render_Tab (T : in Components.Base.UIComponent_Access) is Id : constant Unbounded_String := T.Get_Client_Id; begin if T.all in UITab'Class then Writer.Start_Element ("li"); Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "#" & To_String (Id)); Writer.Write_Text (T.Get_Attribute ("title", Context)); Writer.End_Element ("a"); Writer.End_Element ("li"); end if; end Render_Tab; procedure Render_Tabs is new ASF.Components.Base.Iterate (Process => Render_Tab); begin if UI.Is_Rendered (Context) then declare use Util.Beans.Objects; Id : constant Unbounded_String := UI.Get_Client_Id; Effect : constant Object := UI.Get_Attribute (Context, Name => EFFECT_ATTR_NAME); Collapse : constant Boolean := UI.Get_Attribute (COLLAPSIBLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("id", Id); Writer.Start_Element ("ul"); Render_Tabs (UI); Writer.End_Element ("ul"); Writer.Queue_Script ("$(""#"); Writer.Queue_Script (Id); Writer.Queue_Script (""").tabs({"); if Collapse then Writer.Queue_Script ("collapsible: true"); end if; if not Is_Empty (Effect) then if Collapse then Writer.Queue_Script (","); end if; Writer.Queue_Script ("show:{effect:"""); Writer.Queue_Script (Effect); Writer.Queue_Script (""",duration:"); Writer.Queue_Script (UI.Get_Attribute (DURATION_ATTR_NAME, Context, "500")); Writer.Queue_Script ("}"); end if; Writer.Queue_Script ("});"); end; end if; end Encode_Begin; -- ------------------------------ -- Render the tab view close. -- ------------------------------ overriding procedure Encode_End (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); end if; end Encode_End; -- ------------------------------ -- Render the accordion list and prepare to render the tab contents. -- ------------------------------ overriding procedure Encode_Children (UI : in UIAccordion; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Render_Tab (T : in Components.Base.UIComponent_Access); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; procedure Render_Tab (T : in Components.Base.UIComponent_Access) is begin if T.all in UITab'Class then Writer.Start_Element ("h3"); Writer.Write_Text (T.Get_Attribute ("title", Context)); Writer.End_Element ("h3"); T.Encode_All (Context); end if; end Render_Tab; procedure Render_Tabs is new ASF.Components.Base.Iterate (Process => Render_Tab); begin if UI.Is_Rendered (Context) then declare use Util.Beans.Objects; Id : constant Unbounded_String := UI.Get_Client_Id; Effect : constant Object := UI.Get_Attribute (Context, Name => EFFECT_ATTR_NAME); Collapse : constant Boolean := UI.Get_Attribute (COLLAPSIBLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("id", Id); Render_Tabs (UI); Writer.End_Element ("div"); Writer.Queue_Script ("$(""#"); Writer.Queue_Script (Id); Writer.Queue_Script (""").accordion({"); if Collapse then Writer.Queue_Script ("collapsible: true"); end if; if not Is_Empty (Effect) then if Collapse then Writer.Queue_Script (","); end if; Writer.Queue_Script ("show:{effect:"""); Writer.Queue_Script (Effect); Writer.Queue_Script (""",duration:"); Writer.Queue_Script (UI.Get_Attribute (DURATION_ATTR_NAME, Context, "500")); Writer.Queue_Script ("}"); end if; Writer.Queue_Script ("});"); end; end if; end Encode_Children; end ASF.Components.Widgets.Tabs;
Implement the accordion widget
Implement the accordion widget
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
c60cd59edfce2df4be23e2594f37e1abb74543f6
src/wiki-nodes.adb
src/wiki-nodes.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Nodes is type Tag_Array is array (Html_Tag_Type) of String_Access; HTML_TAG_NAME : aliased constant String := "html"; HEAD_TAG_NAME : aliased constant String := "head"; TITLE_TAG_NAME : aliased constant String := "title"; BASE_TAG_NAME : aliased constant String := "base"; LINK_TAG_NAME : aliased constant String := "link"; META_TAG_NAME : aliased constant String := "meta"; STYLE_TAG_NAME : aliased constant String := "style"; BODY_TAG_NAME : aliased constant String := "body"; ARTICLE_TAG_NAME : aliased constant String := "article"; SECTION_TAG_NAME : aliased constant String := "section"; NAV_TAG_NAME : aliased constant String := "nav"; ASIDE_TAG_NAME : aliased constant String := "aside"; Tag_Names : constant Tag_Array := ( HTML_TAG => HTML_TAG_NAME'Access, HEAD_TAG => HEAD_TAG_NAME'Access, TITLE_TAG => TITLE_TAG_NAME'Access, BASE_TAG => BASE_TAG_NAME'Access, LINK_TAG => LINK_TAG_NAME'Access, META_TAG => META_TAG_NAME'Access, STYLE_TAG => STYLE_TAG_NAME'Access, BODY_TAG => BODY_TAG_NAME'Access, ARTICLE_TAG => ARTICLE_TAG_NAME'Access, SECTION_TAG => SECTION_TAG_NAME'Access, NAV_TAG => NAV_TAG_NAME'Access, ASIDE_TAG => ASIDE_TAG_NAME'Access, others => null ); -- ------------------------------ -- Get the HTML tag name. -- ------------------------------ function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access is begin return Tag_Names (Tag); end Get_Tag_Name; -- ------------------------------ -- Create a text node. -- ------------------------------ function Create_Text (Text : in WString) return Node_Type_Access is begin return new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, others => <>); end Create_Text; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Add_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Document.Current); begin Append (Document.Nodes, Node); Document.Current := Node; end Add_Tag; procedure End_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type) is begin if Document.Current /= null then Document.Current := Document.Current.Parent; end if; end End_Tag; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else if Into.Current.Children = null then Into.Current.Children := new Node_List; end if; Append (Into.Current.Children.all, Node); end if; end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Nodes is type Tag_Array is array (Html_Tag_Type) of String_Access; HTML_TAG_NAME : aliased constant String := "html"; HEAD_TAG_NAME : aliased constant String := "head"; TITLE_TAG_NAME : aliased constant String := "title"; BASE_TAG_NAME : aliased constant String := "base"; LINK_TAG_NAME : aliased constant String := "link"; META_TAG_NAME : aliased constant String := "meta"; STYLE_TAG_NAME : aliased constant String := "style"; BODY_TAG_NAME : aliased constant String := "body"; ARTICLE_TAG_NAME : aliased constant String := "article"; SECTION_TAG_NAME : aliased constant String := "section"; NAV_TAG_NAME : aliased constant String := "nav"; ASIDE_TAG_NAME : aliased constant String := "aside"; Tag_Names : constant Tag_Array := ( HTML_TAG => HTML_TAG_NAME'Access, HEAD_TAG => HEAD_TAG_NAME'Access, TITLE_TAG => TITLE_TAG_NAME'Access, BASE_TAG => BASE_TAG_NAME'Access, LINK_TAG => LINK_TAG_NAME'Access, META_TAG => META_TAG_NAME'Access, STYLE_TAG => STYLE_TAG_NAME'Access, BODY_TAG => BODY_TAG_NAME'Access, ARTICLE_TAG => ARTICLE_TAG_NAME'Access, SECTION_TAG => SECTION_TAG_NAME'Access, NAV_TAG => NAV_TAG_NAME'Access, ASIDE_TAG => ASIDE_TAG_NAME'Access, others => null ); -- ------------------------------ -- Get the HTML tag name. -- ------------------------------ function Get_Tag_Name (Tag : in Html_Tag_Type) return String_Access is begin return Tag_Names (Tag); end Get_Tag_Name; -- ------------------------------ -- Create a text node. -- ------------------------------ function Create_Text (Text : in WString) return Node_Type_Access is begin return new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, others => <>); end Create_Text; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Add_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type; Attributes : in Wiki.Attributes.Attribute_List_Type) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Document.Current); begin Append (Document.Nodes, Node); Document.Current := Node; end Add_Tag; procedure End_Tag (Document : in out Wiki.Nodes.Document; Tag : in Html_Tag_Type) is begin if Document.Current /= null then Document.Current := Document.Current.Parent; end if; end End_Tag; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else if Into.Current.Children = null then Into.Current.Children := new Node_List; end if; Append (Into.Current.Children.all, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); end case; end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; end Wiki.Nodes;
Implement the Append procedure to add a simple node instance
Implement the Append procedure to add a simple node instance
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
a5bafb21169ab1401a3406177490e9cb2f3607fc
src/orka/implementation/orka-terminals.adb
src/orka/implementation/orka-terminals.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Orka.OS; with Orka.Strings; package body Orka.Terminals is Style_Codes : constant array (Style) of Natural := (Default => 0, Bold => 1, Dark => 2, Italic => 3, Underline => 4, Blink => 5, Reversed => 7, Cross_Out => 9); Foreground_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 30, Red => 31, Green => 32, Yellow => 33, Blue => 34, Magenta => 35, Cyan => 36, White => 37); Background_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 40, Red => 41, Green => 42, Yellow => 43, Blue => 44, Magenta => 45, Cyan => 46, White => 47); package L renames Ada.Characters.Latin_1; package SF renames Ada.Strings.Fixed; Reset : constant String := L.ESC & "[0m"; function Sequence (Code : Natural) return String is Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both); begin return (if Code /= 0 then L.ESC & "[" & Image & "m" else ""); end Sequence; function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String is FG : constant String := Sequence (Foreground_Color_Codes (Foreground)); BG : constant String := Sequence (Background_Color_Codes (Background)); ST : constant String := Sequence (Style_Codes (Attribute)); begin return Reset & FG & BG & ST & Text & Reset; end Colorize; ----------------------------------------------------------------------------- Time_Zero : Duration := 0.0; procedure Set_Time_Zero (Time : Duration) is begin Time_Zero := Time; end Set_Time_Zero; Day_In_Seconds : constant := 24.0 * 60.0 * 60.0; function Time_Image return String is Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero; Days_Since_Zero : Natural := 0; begin while Seconds_Since_Zero > Day_In_Seconds loop Seconds_Since_Zero := Seconds_Since_Zero - Day_In_Seconds; Days_Since_Zero := Days_Since_Zero + 1; end loop; declare Seconds_Rounded : constant Natural := Natural (Duration'Max (0.0, Seconds_Since_Zero - 0.5)); Hour : constant Natural := Seconds_Rounded / 3600; Minute : constant Natural := (Seconds_Rounded mod 3600) / 60; Second : constant Natural := Seconds_Rounded mod 60; Sub_Second : constant Duration := Seconds_Since_Zero - Duration (Hour * 3600 + Minute * 60 + Second); -- Remove first character (space) from ' hhmmss' image and then pad it to six digits Image1 : constant String := Natural'Image ((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second); Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0'); -- Insert ':' characters to get 'hh:mm:ss' Image3 : constant String := SF.Insert (Image2, 5, ":"); Image4 : constant String := SF.Insert (Image3, 3, ":"); -- Take image without first character (space) and then pad it to six digits Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6)); Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0'); begin return Image4 & "." & Image6; end; end Time_Image; function Format (Value : Duration; Fore, Aft : Positive) return String is package SF renames Ada.Strings.Fixed; Aft_Shift : constant Positive := 10 ** Aft; New_Value : constant Duration := Duration (Natural (Value * Aft_Shift)) / Aft_Shift; S1 : constant String := SF.Trim (New_Value'Image, Ada.Strings.Both); Index_Decimal : constant Natural := SF.Index (S1, "."); -- Following code assumes that Aft >= 1 (If Aft = 0 then Aft must -- be decremented to remove the decimal point) S2 : constant String := S1 (S1'First .. Natural'Min (S1'Last, Index_Decimal + Aft)); S3 : constant String := SF.Tail (S2, Natural'Max (S2'Length, Fore + 1 + Aft), ' '); begin return S3; end Format; type String_Access is not null access String; Suffices : constant array (1 .. 3) of String_Access := (new String'("s"), new String'("ms"), new String'("us")); function Image (Value : Duration) return String is Number : Duration := Value; Last_Suffix : constant String_Access := Suffices (Suffices'Last); Suffix : String_Access := Suffices (Suffices'First); begin for S of Suffices loop Suffix := S; exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix; Number := Number * 1e3; end loop; begin return Format (Number, Fore => 5, Aft => 3) & " " & Suffix.all; exception when others => return Number'Image & " " & Suffix.all; end; end Image; function Trim (Value : String) return String renames Orka.Strings.Trim; function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term; end Orka.Terminals;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Orka.OS; with Orka.Strings; package body Orka.Terminals is Style_Codes : constant array (Style) of Natural := (Default => 0, Bold => 1, Dark => 2, Italic => 3, Underline => 4, Blink => 5, Reversed => 7, Cross_Out => 9); Foreground_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 30, Red => 31, Green => 32, Yellow => 33, Blue => 34, Magenta => 35, Cyan => 36, White => 37); Background_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 40, Red => 41, Green => 42, Yellow => 43, Blue => 44, Magenta => 45, Cyan => 46, White => 47); package L renames Ada.Characters.Latin_1; package SF renames Ada.Strings.Fixed; Reset : constant String := L.ESC & "[0m"; function Sequence (Code : Natural) return String is Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both); begin return (if Code /= 0 then L.ESC & "[" & Image & "m" else ""); end Sequence; function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String is FG : constant String := Sequence (Foreground_Color_Codes (Foreground)); BG : constant String := Sequence (Background_Color_Codes (Background)); ST : constant String := Sequence (Style_Codes (Attribute)); begin return Reset & FG & BG & ST & Text & Reset; end Colorize; ----------------------------------------------------------------------------- Time_Zero : Duration := 0.0; procedure Set_Time_Zero (Time : Duration) is begin Time_Zero := Time; end Set_Time_Zero; Day_In_Seconds : constant := 24.0 * 60.0 * 60.0; function Time_Image return String is Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero; Days_Since_Zero : Natural := 0; begin while Seconds_Since_Zero > Day_In_Seconds loop Seconds_Since_Zero := Seconds_Since_Zero - Day_In_Seconds; Days_Since_Zero := Days_Since_Zero + 1; end loop; declare Seconds_Rounded : constant Natural := Natural (Duration'Max (0.0, Seconds_Since_Zero - 0.5)); Hour : constant Natural := Seconds_Rounded / 3600; Minute : constant Natural := (Seconds_Rounded mod 3600) / 60; Second : constant Natural := Seconds_Rounded mod 60; Sub_Second : constant Duration := Seconds_Since_Zero - Duration (Hour * 3600 + Minute * 60 + Second); -- Remove first character (space) from ' hhmmss' image and then pad it to six digits Image1 : constant String := Natural'Image ((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second); Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0'); -- Insert ':' characters to get 'hh:mm:ss' Image3 : constant String := SF.Insert (Image2, 5, ":"); Image4 : constant String := SF.Insert (Image3, 3, ":"); -- Take image without first character (space) and then pad it to six digits Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6)); Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0'); begin return Image4 & "." & Image6; end; end Time_Image; function Format (Value : Duration; Fore, Aft : Positive) return String is package SF renames Ada.Strings.Fixed; Aft_Shift : constant Positive := 10 ** Aft; New_Value : constant Duration := Duration (Integer (Value * Aft_Shift)) / Aft_Shift; S1 : constant String := SF.Trim (New_Value'Image, Ada.Strings.Both); Index_Decimal : constant Natural := SF.Index (S1, "."); -- Following code assumes that Aft >= 1 (If Aft = 0 then Aft must -- be decremented to remove the decimal point) S2 : constant String := S1 (S1'First .. Natural'Min (S1'Last, Index_Decimal + Aft)); S3 : constant String := SF.Tail (S2, Natural'Max (S2'Length, Fore + 1 + Aft), ' '); begin return S3; end Format; type String_Access is not null access String; Suffices : constant array (1 .. 3) of String_Access := (new String'("s"), new String'("ms"), new String'("us")); function Image (Value : Duration) return String is Number : Duration := Value; Last_Suffix : constant String_Access := Suffices (Suffices'Last); Suffix : String_Access := Suffices (Suffices'First); begin for S of Suffices loop Suffix := S; exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix; Number := Number * 1e3; end loop; begin return Format (Number, Fore => 5, Aft => 3) & " " & Suffix.all; exception when others => return Number'Image & " " & Suffix.all; end; end Image; function Trim (Value : String) return String renames Orka.Strings.Trim; function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term; end Orka.Terminals;
Fix range check failure in function that formats Durations
orka: Fix range check failure in function that formats Durations Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
84f91dc3c69a4ce37b613cad1dd1998b2a8021ac
src/sys/streams/util-streams.ads
src/sys/streams/util-streams.ads
----------------------------------------------------------------------- -- util-streams -- Stream utilities -- Copyright (C) 2010, 2016, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; -- = Streams = -- The `Util.Streams` package provides several types and operations to allow the -- composition of input and output streams. Input streams can be chained together so that -- they traverse the different stream objects when the data is read from them. Similarly, -- output streams can be chained and the data that is written will traverse the different -- streams from the first one up to the last one in the chain. During such traversal, the -- stream object is able to bufferize the data or make transformations on the data. -- -- The `Input_Stream` interface represents the stream to read data. It only provides a -- `Read` procedure. The `Output_Stream` interface represents the stream to write data. -- It provides a `Write`, `Flush` and `Close` operation. -- -- To use the packages described here, use the following GNAT project: -- -- with "utilada_sys"; -- -- @include util-streams-buffered.ads -- @include util-streams-texts.ads -- @include util-streams-files.ads -- @include util-streams-pipes.ads -- @include util-streams-sockets.ads -- @include util-streams-raw.ads -- @include util-streams-base16.ads -- @include util-streams-base64.ads -- @include util-streams-aes.ads package Util.Streams is pragma Preelaborate; -- ----------------------- -- Output stream -- ----------------------- -- The <b>Output_Stream</b> is an interface that accepts output bytes -- and sends them to a sink. type Output_Stream is limited interface; type Output_Stream_Access is access all Output_Stream'Class; -- Write the buffer array to the output stream. procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- Flush the buffer (if any) to the sink. procedure Flush (Stream : in out Output_Stream) is null; -- Close the sink. procedure Close (Stream : in out Output_Stream) is null; -- ----------------------- -- Input stream -- ----------------------- -- The <b>Input_Stream</b> is the interface that reads input bytes -- from a source and returns them. type Input_Stream is limited interface; type Input_Stream_Access is access all Input_Stream'Class; -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Input_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is abstract; -- Copy the input stream to the output stream until the end of the input stream -- is reached. procedure Copy (From : in out Input_Stream'Class; Into : in out Output_Stream'Class); -- Copy the stream array to the string. -- The string must be large enough to hold the stream array -- or a Constraint_Error exception is raised. procedure Copy (From : in Ada.Streams.Stream_Element_Array; Into : in out String); -- Copy the string to the stream array. -- The stream array must be large enough to hold the string -- or a Constraint_Error exception is raised. procedure Copy (From : in String; Into : in out Ada.Streams.Stream_Element_Array); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream'Class; Item : in Character); procedure Write (Stream : in out Output_Stream'Class; Item : in String); -- Write a wide character on the stream using a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream'Class; Item : in Wide_Wide_Character); procedure Write_Wide (Stream : in out Output_Stream'Class; Item : in Wide_Wide_String); -- Notes: -- ------ -- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b> -- and <b>Input_Stream</b>. It is however not easy to use for composing various -- stream behaviors. end Util.Streams;
----------------------------------------------------------------------- -- util-streams -- Stream utilities -- Copyright (C) 2010, 2016, 2018, 2019, 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.Streams; -- = Streams = -- The `Util.Streams` package provides several types and operations to allow the -- composition of input and output streams. Input streams can be chained together so that -- they traverse the different stream objects when the data is read from them. Similarly, -- output streams can be chained and the data that is written will traverse the different -- streams from the first one up to the last one in the chain. During such traversal, the -- stream object is able to bufferize the data or make transformations on the data. -- -- The `Input_Stream` interface represents the stream to read data. It only provides a -- `Read` procedure. The `Output_Stream` interface represents the stream to write data. -- It provides a `Write`, `Flush` and `Close` operation. -- -- To use the packages described here, use the following GNAT project: -- -- with "utilada_sys"; -- -- @include util-streams-buffered.ads -- @include util-streams-texts.ads -- @include util-streams-files.ads -- @include util-streams-pipes.ads -- @include util-streams-sockets.ads -- @include util-streams-raw.ads -- @include util-streams-buffered-encoders.ads -- @include util-streams-base16.ads -- @include util-streams-base64.ads -- @include util-streams-aes.ads package Util.Streams is pragma Preelaborate; -- ----------------------- -- Output stream -- ----------------------- -- The <b>Output_Stream</b> is an interface that accepts output bytes -- and sends them to a sink. type Output_Stream is limited interface; type Output_Stream_Access is access all Output_Stream'Class; -- Write the buffer array to the output stream. procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- Flush the buffer (if any) to the sink. procedure Flush (Stream : in out Output_Stream) is null; -- Close the sink. procedure Close (Stream : in out Output_Stream) is null; -- ----------------------- -- Input stream -- ----------------------- -- The <b>Input_Stream</b> is the interface that reads input bytes -- from a source and returns them. type Input_Stream is limited interface; type Input_Stream_Access is access all Input_Stream'Class; -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Input_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is abstract; -- Copy the input stream to the output stream until the end of the input stream -- is reached. procedure Copy (From : in out Input_Stream'Class; Into : in out Output_Stream'Class); -- Copy the stream array to the string. -- The string must be large enough to hold the stream array -- or a Constraint_Error exception is raised. procedure Copy (From : in Ada.Streams.Stream_Element_Array; Into : in out String); -- Copy the string to the stream array. -- The stream array must be large enough to hold the string -- or a Constraint_Error exception is raised. procedure Copy (From : in String; Into : in out Ada.Streams.Stream_Element_Array); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream'Class; Item : in Character); procedure Write (Stream : in out Output_Stream'Class; Item : in String); -- Write a wide character on the stream using a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream'Class; Item : in Wide_Wide_Character); procedure Write_Wide (Stream : in out Output_Stream'Class; Item : in Wide_Wide_String); -- Notes: -- ------ -- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b> -- and <b>Input_Stream</b>. It is however not easy to use for composing various -- stream behaviors. end Util.Streams;
Add the buffered encoders documentation
Add the buffered encoders documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
000bc9d7069c31e5faf01db5fcbf0dd557a03df4
src/wiki-streams-html-stream.ads
src/wiki-streams-html-stream.ads
----------------------------------------------------------------------- -- wiki-streams-html-stream -- Generic Wiki HTML output stream -- Copyright (C) 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; generic type Output_Stream is limited new Wiki.Streams.Output_Stream with private; package Wiki.Streams.Html.Stream is type Html_Output_Stream is limited new Output_Stream and Html.Html_Output_Stream with private; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.UString); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Stream : in out Html_Output_Stream; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Stream : in out Html_Output_Stream; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Stream : in out Html_Output_Stream; Content : in Wiki.Strings.WString); private type Html_Output_Stream is limited new Output_Stream and Html.Html_Output_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; end record; end Wiki.Streams.Html.Stream;
----------------------------------------------------------------------- -- wiki-streams-html-stream -- Generic Wiki HTML output stream -- Copyright (C) 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 Wiki.Strings; generic type Output_Stream is limited new Wiki.Streams.Output_Stream with private; package Wiki.Streams.Html.Stream is type Html_Output_Stream is limited new Output_Stream and Html.Html_Output_Stream with private; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.UString); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Stream : in out Html_Output_Stream; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Stream : in out Html_Output_Stream; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Stream : in out Html_Output_Stream; Content : in Wiki.Strings.WString); -- Write an optional newline or space. overriding procedure Newline (Writer : in out Html_Output_Stream); private type Html_Output_Stream is limited new Output_Stream and Html.Html_Output_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 1; Indent_Pos : Natural := 0; Text_Length : Natural := 0; end record; end Wiki.Streams.Html.Stream;
Implement Newline procedure and add support to indent the HTML output stream
Implement Newline procedure and add support to indent the HTML output stream
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
72c063131b4c3cc7aad0bb634c21148b32992595
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- 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.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Serialize.IO.XML; with GNAT.Regexp; package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- 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; -- 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); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- 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); -- 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); private -- 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; -- 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; -- 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 URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; 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.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- 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; -- 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); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- 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); -- 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); private use Util.Strings; -- 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; -- 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; -- 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 URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
Add with clause for Util.Strings
Add with clause for Util.Strings
Ada
apache-2.0
Letractively/ada-security
e2868cc5888e38db5213f65e281729f2669820bc
src/ado-sessions.ads
src/ado-sessions.ads
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Drivers.Connections; with ADO.Queries; with ADO.SQL; with ADO.Caches; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; -- == Session == -- The `ADO.Sessions` package defines the control and management of database sessions. -- The database session is represented by the `Session` or `Master_Session` types. -- It provides operation to create a database statement that can be executed. -- The `Session` type is used to represent read-only database sessions. It provides -- operations to query the database but it does not allow to update or delete content. -- The `Master_Session` type extends the `Session` type to provide write -- access and it provides operations to get update or delete statements. The differentiation -- between the two sessions is provided for the support of database replications with -- databases such as MySQL. -- -- @include ado-sessions-factory.ads -- @include ado-sequences.ads -- package ADO.Sessions is use ADO.Statements; -- Raised for all errors reported by the database DB_Error : exception; -- Raised if the database connection is not open. NOT_OPEN : exception; NOT_FOUND : exception; NO_DATABASE : exception; -- Raised when the connection URI is invalid. Connection_Error : exception; -- The database connection status type Connection_Status is (OPEN, CLOSED); type Object_Factory is tagged private; -- --------- -- Session -- --------- -- Read-only database connection (or slave connection). -- type Session is tagged private; -- Get the session status. function Get_Status (Database : in Session) return Connection_Status; -- Get the database driver which manages this connection. function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access; -- Close the session. procedure Close (Database : in out Session); -- Insert a new cache in the manager. The cache is identified by the given name. procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access); -- Attach the object to the session. procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class); -- Check if the session contains the object identified by the given key. function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean; -- Remove the object from the session cache. procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in String) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement; -- Create a query statement and initialize the SQL statement with the query definition. function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition); -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; -- --------- -- Master Session -- --------- -- Read-write session. -- type Master_Session is new Session with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Session); -- Commit the current transaction. procedure Commit (Database : in out Master_Session); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Session); -- Allocate an identifier for the table. procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class); -- Flush the objects that were modified. procedure Flush (Database : in out Master_Session); -- Create a delete statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an update statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- Create an insert statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache; type Object_Factory is tagged record A : Integer; end record; type Object_Factory_Access is access all Object_Factory'Class; -- The <b>Session_Record</b> maintains the connection information to the database for -- the duration of the session. It also maintains a cache of application objects -- which is used when session objects are fetched (either through Load or a Find). -- The connection is released and the session record is deleted when the session -- is closed with <b>Close</b>. -- -- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b> -- object that allows to give access to the session record associated with the object. -- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply -- unlinked from the session record. type Session_Record is limited record Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Database : ADO.Drivers.Connections.Ref.Ref; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_Access; Values : ADO.Caches.Cache_Manager_Access; Queries : ADO.Queries.Query_Manager_Access; end record; type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access := null; end record; overriding procedure Adjust (Object : in out Session); overriding procedure Finalize (Object : in out Session); type Factory_Access is access all ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; end record; procedure Check_Session (Database : in Session'Class; Message : in String := ""); pragma Inline (Check_Session); end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Drivers.Connections; with ADO.Queries; with ADO.SQL; with ADO.Caches; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; -- = Session = -- The `ADO.Sessions` package defines the control and management of database sessions. -- The database session is represented by the `Session` or `Master_Session` types. -- It provides operation to create a database statement that can be executed. -- The `Session` type is used to represent read-only database sessions. It provides -- operations to query the database but it does not allow to update or delete content. -- The `Master_Session` type extends the `Session` type to provide write -- access and it provides operations to get update or delete statements. The differentiation -- between the two sessions is provided for the support of database replications with -- databases such as MySQL. -- -- @include ado-sessions-sources.ads -- @include ado-sessions-factory.ads -- @include ado-caches.ads package ADO.Sessions is use ADO.Statements; -- Raised for all errors reported by the database DB_Error : exception; -- Raised if the database connection is not open. NOT_OPEN : exception; NOT_FOUND : exception; NO_DATABASE : exception; -- Raised when the connection URI is invalid. Connection_Error : exception; -- The database connection status type Connection_Status is (OPEN, CLOSED); type Object_Factory is tagged private; -- --------- -- Session -- --------- -- Read-only database connection (or slave connection). -- type Session is tagged private; -- Get the session status. function Get_Status (Database : in Session) return Connection_Status; -- Get the database driver which manages this connection. function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access; -- Close the session. procedure Close (Database : in out Session); -- Insert a new cache in the manager. The cache is identified by the given name. procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access); -- Attach the object to the session. procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class); -- Check if the session contains the object identified by the given key. function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean; -- Remove the object from the session cache. procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in String) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement; -- Create a query statement and initialize the SQL statement with the query definition. function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition); -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; -- --------- -- Master Session -- --------- -- Read-write session. -- type Master_Session is new Session with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Session); -- Commit the current transaction. procedure Commit (Database : in out Master_Session); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Session); -- Allocate an identifier for the table. procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class); -- Flush the objects that were modified. procedure Flush (Database : in out Master_Session); -- Create a delete statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an update statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- Create an insert statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache; type Object_Factory is tagged record A : Integer; end record; type Object_Factory_Access is access all Object_Factory'Class; -- The <b>Session_Record</b> maintains the connection information to the database for -- the duration of the session. It also maintains a cache of application objects -- which is used when session objects are fetched (either through Load or a Find). -- The connection is released and the session record is deleted when the session -- is closed with <b>Close</b>. -- -- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b> -- object that allows to give access to the session record associated with the object. -- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply -- unlinked from the session record. type Session_Record is limited record Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Database : ADO.Drivers.Connections.Ref.Ref; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_Access; Values : ADO.Caches.Cache_Manager_Access; Queries : ADO.Queries.Query_Manager_Access; end record; type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access := null; end record; overriding procedure Adjust (Object : in out Session); overriding procedure Finalize (Object : in out Session); type Factory_Access is access all ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; end record; procedure Check_Session (Database : in Session'Class; Message : in String := ""); pragma Inline (Check_Session); end ADO.Sessions;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
94ee8b52ff326e791d4cee7ddc9424eb50705d06
src/asf-sessions.ads
src/asf-sessions.ads
----------------------------------------------------------------------- -- 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 EL.Objects; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Unbounded; with ASF.Principals; private with Util.Beans.Objects.Maps; private with Util.Concurrent.Locks; private with Util.Concurrent.Counters; -- The <b>ASF.Sessions</b> package is an Ada implementation of the -- Java servlet Specification (See JSR 315 at jcp.org). package ASF.Sessions is -- Raised if there is no session. No_Session : exception; -- The default session inactive timeout. DEFAULT_INACTIVE_TIMEOUT : constant Duration := 300.0; -- Provides a way to identify a user across more than one page request -- or visit to a Web site and to store information about that user. -- -- The servlet container uses this interface to create a session between -- an HTTP client and an HTTP server. The session persists for a specified -- time period, across more than one connection or page request from the user. -- A session usually corresponds to one user, who may visit a site many times. -- The server can maintain a session in many ways such as using cookies -- or rewriting URLs. -- -- This interface allows servlets to -- * View and manipulate information about a session, such as the session -- identifier, creation time, and last accessed time -- * Bind objects to sessions, allowing user information to persist across -- multiple user connections -- -- A servlet should be able to handle cases in which the client does not -- choose to join a session, such as when cookies are intentionally turned off. -- Until the client joins the session, isNew returns true. If the client chooses -- not to join the session, getSession will return a different session on each -- request, and isNew will always return true. -- -- Session information is scoped only to the current web application (ServletContext), -- so information stored in one context will not be directly visible in another. type Session is tagged private; -- Returns true if the session is valid. function Is_Valid (Sess : in Session'Class) return Boolean; -- 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; -- 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; -- 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; -- 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); -- 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; -- 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); -- 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); -- 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; -- Sets the principal associated with the session. procedure Set_Principal (Sess : in out Session; Principal : in ASF.Principals.Principal_Access); -- Invalidates this session then unbinds any objects bound to it. procedure Invalidate (Sess : in out Session); Null_Session : constant Session; private type Session_Record; type Session_Record_Access is access all Session_Record'Class; type Session_Record is new Ada.Finalization.Limited_Controlled with record -- Reference counter. Ref_Counter : Util.Concurrent.Counters.Counter; -- RW lock to protect access to members. Lock : Util.Concurrent.Locks.RW_Lock; -- Attributes bound to this session. Attributes : aliased Util.Beans.Objects.Maps.Map; -- Time when the session was created. Create_Time : Ada.Calendar.Time; -- Time when the session was last accessed. Access_Time : Ada.Calendar.Time; -- Max inactive time in seconds. Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT; -- Session identifier. Id : Ada.Strings.Unbounded.String_Access; -- True if the session is active. Is_Active : Boolean := True; -- When not null, the principal that authenticated to this session. Principal : ASF.Principals.Principal_Access := null; end record; overriding procedure Finalize (Object : in out Session_Record); type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access; end record; -- Adjust (increment) the session record reference counter. overriding procedure Adjust (Object : in out Session); -- 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); Null_Session : constant Session := Session'(Ada.Finalization.Controlled with Impl => null); end ASF.Sessions;
----------------------------------------------------------------------- -- asf-sessions -- ASF Sessions -- Copyright (C) 2010, 2011, 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.Sessions; package ASF.Sessions renames Servlet.Sessions;
Package ASF.Sessions moved to Servlet.Sessions
Package ASF.Sessions moved to Servlet.Sessions
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
9994dbbcd7fc1d11bd570096946de84457e8b017
src/atlas-server.adb
src/atlas-server.adb
----------------------------------------------------------------------- -- Atlas-server -- Application server -- 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.Exceptions; with Util.Log.Loggers; with ASF.Server.Web; with Atlas.Applications; procedure Atlas.Server is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; WS : ASF.Server.Web.AWS_Container; begin Atlas.Applications.Initialize (App); WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access); Log.Info ("Connect you browser to: http://localhost:8080/atlas/index.html"); WS.Start; delay 365.0 * 24.0 * 3600.0; App.Close; exception when E : others => Log.Error ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Atlas.Server;
----------------------------------------------------------------------- -- Atlas-server -- Application server -- Copyright (C) 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.Exceptions; with Util.Log.Loggers; with AWS.Config.Set; with ASF.Server.Web; with AWA.Setup.Applications; with Atlas.Applications; procedure Atlas.Server is procedure Configure (Config : in out AWS.Config.Object); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; WS : ASF.Server.Web.AWS_Container; Setup : AWA.Setup.Applications.Application; procedure Configure (Config : in out AWS.Config.Object) is begin AWS.Config.Set.Input_Line_Size_Limit (1_000_000); AWS.Config.Set.Max_Connection (Config, 2); AWS.Config.Set.Accept_Queue_Size (Config, 100); AWS.Config.Set.Send_Buffer_Size (Config, 128 * 1024); AWS.Config.Set.Upload_Size_Limit (Config, 100_000_000); end Configure; begin WS.Configure (Configure'Access); WS.Start; Setup.Setup ("atlas.properties", WS); Atlas.Applications.Initialize (App); WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access); Log.Info ("Connect you browser to: http://localhost:8080/atlas/index.html"); -- WS.Start; delay 365.0 * 24.0 * 3600.0; App.Close; exception when E : others => Log.Error ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Atlas.Server;
Add the setup application to configure the Atlas application
Add the setup application to configure the Atlas application
Ada
apache-2.0
stcarrez/atlas
422367feddc010976ef64966fada4bed5caf3353
src/asf-components-html-forms.ads
src/asf-components-html-forms.ads
----------------------------------------------------------------------- -- html.forms -- ASF HTML Form Components -- 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.Components.Holders; with ASF.Components.Html.Text; with ASF.Validators; with ASF.Events.Faces; with EL.Objects; with EL.Expressions; package ASF.Components.Html.Forms is -- A UIComponent can have several validators. To keep the implementation light and -- simple, a fixed array is used. Most components will have one or two validators. -- Define the number of validators per component (UIInput). MAX_VALIDATORS_PER_COMPONENT : constant Positive := 5; -- Message displayed when the submitted value is required but is empty. REQUIRED_MESSAGE_ID : constant String := "asf.faces.component.UIInput.REQUIRED"; -- ------------------------------ -- Form Component -- ------------------------------ type UIForm is new UIHtmlComponent with private; type UIForm_Access is access all UIForm'Class; -- Check whether the form is submitted. function Is_Submitted (UI : in UIForm) return Boolean; -- Called during the <b>Apply Request</b> phase to indicate that this -- form is submitted. procedure Set_Submitted (UI : in out UIForm); -- Get the action URL to set on the HTML form function Get_Action (UI : in UIForm; Context : in Faces_Context'Class) return String; overriding procedure Encode_Begin (UI : in UIForm; Context : in out Faces_Context'Class); overriding procedure Encode_End (UI : in UIForm; Context : in out Faces_Context'Class); overriding procedure Decode (UI : in out UIForm; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIForm; Context : in out Faces_Context'Class); -- ------------------------------ -- Input Component -- ------------------------------ type UIInput is new Text.UIOutput and Holders.Editable_Value_Holder with private; type UIInput_Access is access all UIInput'Class; -- Check if this component has the required attribute set. function Is_Required (UI : in UIInput; Context : in Faces_Context'Class) return Boolean; -- Find the form component which contains the input component. -- Returns null if the input is not within a form component. function Get_Form (UI : in UIInput) return UIForm_Access; -- Get the value of the component. If the component has a submitted value, returns it. -- If the component has a local value which is not null, returns it. -- Otherwise, if we have a Value_Expression evaluate and returns the value. overriding function Get_Value (UI : in UIInput) return EL.Objects.Object; -- Set the input component as a password field. procedure Set_Secret (UI : in out UIInput; Value : in Boolean); -- Render the input element. procedure Render_Input (UI : in UIInput; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); overriding procedure Encode_Begin (UI : in UIInput; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIInput; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> procedure Process_Validators (UI : in out UIInput; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIInput; Context : in out Faces_Context'Class); -- Validate the submitted value. -- <ul> -- <li>Retreive the submitted value -- <li>If the value is null, exit without further processing. -- <li>Validate the value by calling <b>Validate_Value</b> -- </ul> procedure Validate (UI : in out UIInput; Context : in out Faces_Context'Class); -- Set the <b>valid</b> property: -- <ul> -- <li>If the <b>required</b> property is true, ensure the -- value is not empty -- <li>Call the <b>Validate</b> procedure on each validator -- registered on this component. -- <li>Set the <b>valid</b> property if all validator passed. -- </ul> procedure Validate_Value (UI : in out UIInput; Value : in EL.Objects.Object; Context : in out Faces_Context'Class); -- Add the validator to be used on the component. The ASF implementation limits -- to 5 the number of validators that can be set on a component (See UIInput). -- The validator instance will be freed when the editable value holder is deleted -- unless <b>Shared</b> is true. overriding procedure Add_Validator (UI : in out UIInput; Validator : in ASF.Validators.Validator_Access; Shared : in Boolean := False); -- Delete the UI input instance. overriding procedure Finalize (UI : in out UIInput); -- ------------------------------ -- InputTextarea Component -- ------------------------------ type UIInputTextarea is new UIInput with private; type UIInputTextarea_Access is access all UIInputTextarea'Class; -- Render the textarea element. overriding procedure Render_Input (UI : in UIInputTextarea; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- ------------------------------ -- Input_Hidden Component -- ------------------------------ type UIInput_Hidden is new UIInput with private; type UIInput_Hidden_Access is access all UIInput_Hidden'Class; -- Render the inputHidden element. overriding procedure Render_Input (UI : in UIInput_Hidden; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- ------------------------------ -- InputFile Component -- ------------------------------ type UIInput_File is new UIInput with private; type UIInput_File_Access is access all UIInput_File'Class; -- Render the input file element. overriding procedure Render_Input (UI : in UIInput_File; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- Validate the submitted file. -- <ul> -- <li>Retreive the submitted value -- <li>If the value is null, exit without further processing. -- <li>Validate the value by calling <b>Validate_Value</b> -- </ul> overriding procedure Validate (UI : in out UIInput_File; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIInput_File; Context : in out Faces_Context'Class); -- ------------------------------ -- Button Component -- ------------------------------ type UICommand is new UIHtmlComponent with private; overriding procedure Encode_Begin (UI : in UICommand; Context : in out Faces_Context'Class); -- Get the value to write on the output. function Get_Value (UI : in UICommand) return EL.Objects.Object; -- Set the value to write on the output. procedure Set_Value (UI : in out UICommand; Value : in EL.Objects.Object); -- Get the action method expression to invoke if the command is pressed. function Get_Action_Expression (UI : in UICommand; Context : in Faces_Context'Class) return EL.Expressions.Method_Expression; overriding procedure Process_Decodes (UI : in out UICommand; Context : in out Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out UICommand; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class); private type Validator is record Validator : ASF.Validators.Validator_Access := null; Shared : Boolean := False; end record; type Validator_Array is array (1 .. MAX_VALIDATORS_PER_COMPONENT) of Validator; type UIInput is new Text.UIOutput and Holders.Editable_Value_Holder with record Submitted_Value : EL.Objects.Object; Is_Valid : Boolean := False; Is_Secret : Boolean := False; Validators : Validator_Array; end record; type UIInputTextarea is new UIInput with record Rows : Natural; Cols : Natural; end record; type UIInput_Hidden is new UIInput with null record; type UIInput_File is new UIInput with null record; type UICommand is new UIHtmlComponent with record Value : EL.Objects.Object; end record; type UIForm is new UIHtmlComponent with record Is_Submitted : Boolean := False; end record; end ASF.Components.Html.Forms;
----------------------------------------------------------------------- -- html.forms -- ASF HTML Form Components -- Copyright (C) 2010, 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Holders; with ASF.Components.Html.Text; with ASF.Validators; with ASF.Events.Faces; with EL.Objects; with EL.Expressions; package ASF.Components.Html.Forms is -- A UIComponent can have several validators. To keep the implementation light and -- simple, a fixed array is used. Most components will have one or two validators. -- Define the number of validators per component (UIInput). MAX_VALIDATORS_PER_COMPONENT : constant Positive := 5; -- Message displayed when the submitted value is required but is empty. REQUIRED_MESSAGE_ID : constant String := "asf.faces.component.UIInput.REQUIRED"; -- ------------------------------ -- Form Component -- ------------------------------ type UIForm is new UIHtmlComponent with private; type UIForm_Access is access all UIForm'Class; -- Check whether the form is submitted. function Is_Submitted (UI : in UIForm) return Boolean; -- Called during the <b>Apply Request</b> phase to indicate that this -- form is submitted. procedure Set_Submitted (UI : in out UIForm); -- Get the action URL to set on the HTML form function Get_Action (UI : in UIForm; Context : in Faces_Context'Class) return String; overriding procedure Encode_Begin (UI : in UIForm; Context : in out Faces_Context'Class); overriding procedure Encode_End (UI : in UIForm; Context : in out Faces_Context'Class); overriding procedure Decode (UI : in out UIForm; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIForm; Context : in out Faces_Context'Class); -- ------------------------------ -- Input Component -- ------------------------------ type UIInput is new Text.UIOutput and Holders.Editable_Value_Holder with private; type UIInput_Access is access all UIInput'Class; -- Check if this component has the required attribute set. function Is_Required (UI : in UIInput; Context : in Faces_Context'Class) return Boolean; -- Find the form component which contains the input component. -- Returns null if the input is not within a form component. function Get_Form (UI : in UIInput) return UIForm_Access; -- Get the value of the component. If the component has a submitted value, returns it. -- If the component has a local value which is not null, returns it. -- Otherwise, if we have a Value_Expression evaluate and returns the value. overriding function Get_Value (UI : in UIInput) return EL.Objects.Object; -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. function Get_Parameter (UI : in UIInput; Context : in Faces_Context'Class) return String; -- Set the input component as a password field. procedure Set_Secret (UI : in out UIInput; Value : in Boolean); -- Render the input element. procedure Render_Input (UI : in UIInput; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); overriding procedure Encode_Begin (UI : in UIInput; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIInput; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> procedure Process_Validators (UI : in out UIInput; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIInput; Context : in out Faces_Context'Class); -- Validate the submitted value. -- <ul> -- <li>Retreive the submitted value -- <li>If the value is null, exit without further processing. -- <li>Validate the value by calling <b>Validate_Value</b> -- </ul> procedure Validate (UI : in out UIInput; Context : in out Faces_Context'Class); -- Set the <b>valid</b> property: -- <ul> -- <li>If the <b>required</b> property is true, ensure the -- value is not empty -- <li>Call the <b>Validate</b> procedure on each validator -- registered on this component. -- <li>Set the <b>valid</b> property if all validator passed. -- </ul> procedure Validate_Value (UI : in out UIInput; Value : in EL.Objects.Object; Context : in out Faces_Context'Class); -- Add the validator to be used on the component. The ASF implementation limits -- to 5 the number of validators that can be set on a component (See UIInput). -- The validator instance will be freed when the editable value holder is deleted -- unless <b>Shared</b> is true. overriding procedure Add_Validator (UI : in out UIInput; Validator : in ASF.Validators.Validator_Access; Shared : in Boolean := False); -- Delete the UI input instance. overriding procedure Finalize (UI : in out UIInput); -- ------------------------------ -- InputTextarea Component -- ------------------------------ type UIInputTextarea is new UIInput with private; type UIInputTextarea_Access is access all UIInputTextarea'Class; -- Render the textarea element. overriding procedure Render_Input (UI : in UIInputTextarea; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- ------------------------------ -- Input_Hidden Component -- ------------------------------ type UIInput_Hidden is new UIInput with private; type UIInput_Hidden_Access is access all UIInput_Hidden'Class; -- Render the inputHidden element. overriding procedure Render_Input (UI : in UIInput_Hidden; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- ------------------------------ -- InputFile Component -- ------------------------------ type UIInput_File is new UIInput with private; type UIInput_File_Access is access all UIInput_File'Class; -- Render the input file element. overriding procedure Render_Input (UI : in UIInput_File; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- Validate the submitted file. -- <ul> -- <li>Retreive the submitted value -- <li>If the value is null, exit without further processing. -- <li>Validate the value by calling <b>Validate_Value</b> -- </ul> overriding procedure Validate (UI : in out UIInput_File; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIInput_File; Context : in out Faces_Context'Class); -- ------------------------------ -- Button Component -- ------------------------------ type UICommand is new UIHtmlComponent with private; overriding procedure Encode_Begin (UI : in UICommand; Context : in out Faces_Context'Class); -- Get the value to write on the output. function Get_Value (UI : in UICommand) return EL.Objects.Object; -- Set the value to write on the output. procedure Set_Value (UI : in out UICommand; Value : in EL.Objects.Object); -- Get the action method expression to invoke if the command is pressed. function Get_Action_Expression (UI : in UICommand; Context : in Faces_Context'Class) return EL.Expressions.Method_Expression; overriding procedure Process_Decodes (UI : in out UICommand; Context : in out Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out UICommand; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class); private type Validator is record Validator : ASF.Validators.Validator_Access := null; Shared : Boolean := False; end record; type Validator_Array is array (1 .. MAX_VALIDATORS_PER_COMPONENT) of Validator; type UIInput is new Text.UIOutput and Holders.Editable_Value_Holder with record Submitted_Value : EL.Objects.Object; Is_Valid : Boolean := False; Is_Secret : Boolean := False; Validators : Validator_Array; end record; type UIInputTextarea is new UIInput with record Rows : Natural; Cols : Natural; end record; type UIInput_Hidden is new UIInput with null record; type UIInput_File is new UIInput with null record; type UICommand is new UIHtmlComponent with record Value : EL.Objects.Object; end record; type UIForm is new UIHtmlComponent with record Is_Submitted : Boolean := False; end record; end ASF.Components.Html.Forms;
Declare the Get_Parameter function for UIInput tagged record
Declare the Get_Parameter function for UIInput tagged record
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
d58259982f567cb06280f00d9fb774e48acbcbcb
src/asf-contexts-writer.adb
src/asf-contexts-writer.adb
----------------------------------------------------------------------- -- writer -- Response stream writer -- 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 Unicode; package body ASF.Contexts.Writer is use Unicode; procedure Write_Escape (Stream : in out ResponseWriter'Class; Char : in Character); -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out ResponseWriter'Class); -- ------------------------------ -- Response Writer -- ------------------------------ -- ------------------------------ -- 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 ResponseWriter; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream) is begin Stream.Initialize (Output); Stream.Content_Type := To_Unbounded_String (Content_Type); Stream.Encoding := Unicode.Encodings.Get_By_Name (Encoding); end Initialize; -- ------------------------------ -- Flush the response stream and release the buffer. -- ------------------------------ procedure Finalize (Object : in out ResponseWriter) is begin Object.Flush; end Finalize; -- ------------------------------ -- Get the content type. -- ------------------------------ function Get_Content_Type (Stream : in ResponseWriter) return String is begin return To_String (Stream.Content_Type); end Get_Content_Type; -- ------------------------------ -- Get the character encoding. -- ------------------------------ function Get_Encoding (Stream : in ResponseWriter) return String is begin return Stream.Encoding.Name.all; end Get_Encoding; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out ResponseWriter'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; end if; end Close_Current; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ procedure Start_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Write ('<'); Stream.Write (Name); Stream.Close_Start := True; end Start_Element; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ procedure Start_Optional_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Optional_Element (1 .. Name'Length) := Name; Stream.Optional_Element_Size := Name'Length; end Start_Optional_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ procedure End_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end End_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ procedure End_Optional_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); if Stream.Optional_Element_Written then Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end if; Stream.Optional_Element_Written := False; Stream.Optional_Element_Size := 0; end End_Optional_Element; -- ------------------------------ -- 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 ResponseWriter; Name : in String; Content : in String) is begin Stream.Start_Element (Name); Stream.Write_Text (Content); Stream.End_Element (Name); end Write_Element; procedure Write_Wide_Element (Stream : in out ResponseWriter; Name : in String; Content : in Wide_Wide_String) is begin Stream.Start_Element (Name); Stream.Write_Wide_Text (Content); Stream.End_Element (Name); end Write_Wide_Element; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in String) is begin -- If we have an optional element, start it. if Stream.Optional_Element_Size > 0 and not Stream.Optional_Element_Written then Stream.Write ('<'); Stream.Write (Stream.Optional_Element (1 .. Stream.Optional_Element_Size)); Stream.Close_Start := True; Stream.Optional_Element_Written := True; end if; if Stream.Close_Start then Stream.Write (' '); Stream.Write (Name); Stream.Write ('='); Stream.Write ('"'); for I in Value'Range loop declare C : constant Character := Value (I); begin if C = '"' then Stream.Write ("&quot;"); else Stream.Write_Escape (C); end if; end; end loop; Stream.Write ('"'); end if; end Write_Attribute; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in Unbounded_String) is begin Stream.Write_Attribute (Name, To_String (Value)); end Write_Attribute; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in EL.Objects.Object) is S : constant String := EL.Objects.To_String (Value); begin Stream.Write_Attribute (Name, S); end Write_Attribute; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ procedure Write_Text (Stream : in out ResponseWriter; Text : in String) is begin for I in Text'Range loop ResponseWriter'Class (Stream).Write_Char (Text (I)); end loop; end Write_Text; procedure Write_Text (Stream : in out ResponseWriter; Text : in Unbounded_String) is Count : constant Natural := Length (Text); begin if Count > 0 then for I in 1 .. Count loop ResponseWriter'Class (Stream).Write_Char (Element (Text, I)); end loop; end if; end Write_Text; procedure Write_Wide_Text (Stream : in out ResponseWriter; Text : in Wide_Wide_String) is begin for I in Text'Range loop ResponseWriter'Class (Stream).Write_Wide_Char (Text (I)); end loop; end Write_Wide_Text; procedure Write_Text (Stream : in out ResponseWriter; Value : in EL.Objects.Object) is use EL.Objects; Of_Type : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value); begin case Of_Type is when TYPE_BOOLEAN => Close_Current (Stream); if To_Boolean (Value) then ResponseWriter'Class (Stream).Write ("true"); else ResponseWriter'Class (Stream).Write ("false"); end if; when TYPE_INTEGER | TYPE_FLOAT => Close_Current (Stream); ResponseWriter'Class (Stream).Write (To_String (Value)); when TYPE_STRING => ResponseWriter'Class (Stream).Write_Text (To_String (Value)); when others => ResponseWriter'Class (Stream).Write_Wide_Text (To_Wide_Wide_String (Value)); end case; end Write_Text; -- ------------------------------ -- Write a character on the response stream and escape that character -- as necessary. -- ------------------------------ procedure Write_Char (Stream : in out ResponseWriter; Char : in Character) is begin Close_Current (Stream); Write_Escape (Stream, Char); end Write_Char; -- ------------------------------ -- Internal method to write a character on the response stream -- and escape that character as necessary. Unlike 'Write_Char', -- this operation does not closes the current XML entity. -- ------------------------------ procedure Write_Escape (Stream : in out ResponseWriter'Class; Char : in Character) is Code : constant Unicode_Char := Character'Pos (Char); begin -- Tilde or less... if Code < 16#A0# then -- If "?" or over, no escaping is needed (this covers -- most of the Latin alphabet) if Code > 16#3F# or Code <= 16#20# then Stream.Write (Char); elsif Char = '<' then Stream.Write ("&lt;"); elsif Char = '>' then Stream.Write ("&gt;"); elsif Char = '&' then Stream.Write ("&amp;"); else Stream.Write (Char); end if; else declare S : String (1 .. 5) := "&#00;"; C : Unicode_Char; begin C := Code and 16#0F#; if C > 10 then S (4) := Character'Val (C - 10 + Character'Pos ('A')); else S (4) := Character'Val (C + Character'Pos ('0')); end if; C := (Code / 16) and 16#0F#; if C > 10 then S (3) := Character'Val (C - 10 + Character'Pos ('A')); else S (3) := Character'Val (C + Character'Pos ('0')); end if; Stream.Write (S); end; end if; end Write_Escape; -- ------------------------------ -- Write a character on the response stream and escape that character -- as necessary. -- ------------------------------ procedure Write_Wide_Char (Stream : in out ResponseWriter; Char : in Wide_Wide_Character) is Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char); begin Close_Current (Stream); -- Tilde or less... if Code < 16#100# then Stream.Write_Char (Character'Val (Code)); else declare S : String (1 .. 5) := "&#00;"; C : Unicode_Char; begin C := Code and 16#0F#; if C > 10 then S (4) := Character'Val (C - 10 + Character'Pos ('A')); else S (4) := Character'Val (C + Character'Pos ('0')); end if; C := (Code / 16) and 16#0F#; if C > 10 then S (3) := Character'Val (C - 10 + Character'Pos ('A')); else S (3) := Character'Val (C + Character'Pos ('0')); end if; Stream.Write (S); end; end if; end Write_Wide_Char; -- ------------------------------ -- Write a string on the stream. -- ------------------------------ procedure Write (Stream : in out ResponseWriter; Item : in Ada.Strings.Unbounded.Unbounded_String) is begin Close_Current (Stream); ASF.Streams.Print_Stream (Stream).Write (Item); end Write; end ASF.Contexts.Writer;
----------------------------------------------------------------------- -- writer -- Response stream writer -- 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 Unicode; package body ASF.Contexts.Writer is use Unicode; procedure Write_Escape (Stream : in out ResponseWriter'Class; Char : in Character); -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out ResponseWriter'Class); -- ------------------------------ -- Response Writer -- ------------------------------ -- ------------------------------ -- 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 ResponseWriter; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream) is begin Stream.Initialize (Output); Stream.Content_Type := To_Unbounded_String (Content_Type); Stream.Encoding := Unicode.Encodings.Get_By_Name (Encoding); end Initialize; -- ------------------------------ -- Flush the response stream and release the buffer. -- ------------------------------ procedure Finalize (Object : in out ResponseWriter) is begin Object.Flush; end Finalize; -- ------------------------------ -- Get the content type. -- ------------------------------ function Get_Content_Type (Stream : in ResponseWriter) return String is begin return To_String (Stream.Content_Type); end Get_Content_Type; -- ------------------------------ -- Get the character encoding. -- ------------------------------ function Get_Encoding (Stream : in ResponseWriter) return String is begin return Stream.Encoding.Name.all; end Get_Encoding; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out ResponseWriter'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; end if; end Close_Current; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ procedure Start_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Write ('<'); Stream.Write (Name); Stream.Close_Start := True; end Start_Element; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ procedure Start_Optional_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Optional_Element (1 .. Name'Length) := Name; Stream.Optional_Element_Size := Name'Length; end Start_Optional_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ procedure End_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end End_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ procedure End_Optional_Element (Stream : in out ResponseWriter; Name : in String) is begin Close_Current (Stream); if Stream.Optional_Element_Written then Stream.Write ("</"); Stream.Write (Name); Stream.Write ('>'); end if; Stream.Optional_Element_Written := False; Stream.Optional_Element_Size := 0; end End_Optional_Element; -- ------------------------------ -- 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 ResponseWriter; Name : in String; Content : in String) is begin Stream.Start_Element (Name); Stream.Write_Text (Content); Stream.End_Element (Name); end Write_Element; procedure Write_Wide_Element (Stream : in out ResponseWriter; Name : in String; Content : in Wide_Wide_String) is begin Stream.Start_Element (Name); Stream.Write_Wide_Text (Content); Stream.End_Element (Name); end Write_Wide_Element; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in String) is begin -- If we have an optional element, start it. if Stream.Optional_Element_Size > 0 and not Stream.Optional_Element_Written then Stream.Write ('<'); Stream.Write (Stream.Optional_Element (1 .. Stream.Optional_Element_Size)); Stream.Close_Start := True; Stream.Optional_Element_Written := True; end if; if Stream.Close_Start then Stream.Write (' '); Stream.Write (Name); Stream.Write ('='); Stream.Write ('"'); for I in Value'Range loop declare C : constant Character := Value (I); begin if C = '"' then Stream.Write ("&quot;"); else Stream.Write_Escape (C); end if; end; end loop; Stream.Write ('"'); end if; end Write_Attribute; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in Unbounded_String) is begin Stream.Write_Attribute (Name, To_String (Value)); end Write_Attribute; procedure Write_Attribute (Stream : in out ResponseWriter; Name : in String; Value : in EL.Objects.Object) is S : constant String := EL.Objects.To_String (Value); begin Stream.Write_Attribute (Name, S); end Write_Attribute; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ procedure Write_Text (Stream : in out ResponseWriter; Text : in String) is begin for I in Text'Range loop ResponseWriter'Class (Stream).Write_Char (Text (I)); end loop; end Write_Text; procedure Write_Text (Stream : in out ResponseWriter; Text : in Unbounded_String) is Count : constant Natural := Length (Text); begin if Count > 0 then for I in 1 .. Count loop ResponseWriter'Class (Stream).Write_Char (Element (Text, I)); end loop; end if; end Write_Text; procedure Write_Wide_Text (Stream : in out ResponseWriter; Text : in Wide_Wide_String) is begin for I in Text'Range loop ResponseWriter'Class (Stream).Write_Wide_Char (Text (I)); end loop; end Write_Wide_Text; procedure Write_Text (Stream : in out ResponseWriter; Value : in EL.Objects.Object) is use EL.Objects; Of_Type : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value); begin case Of_Type is when TYPE_BOOLEAN => Close_Current (Stream); if To_Boolean (Value) then ResponseWriter'Class (Stream).Write ("true"); else ResponseWriter'Class (Stream).Write ("false"); end if; when TYPE_INTEGER | TYPE_FLOAT => Close_Current (Stream); ResponseWriter'Class (Stream).Write (To_String (Value)); when TYPE_STRING => ResponseWriter'Class (Stream).Write_Text (To_String (Value)); when others => ResponseWriter'Class (Stream).Write_Wide_Text (To_Wide_Wide_String (Value)); end case; end Write_Text; -- ------------------------------ -- Write a character on the response stream and escape that character -- as necessary. -- ------------------------------ procedure Write_Char (Stream : in out ResponseWriter; Char : in Character) is begin Close_Current (Stream); Write_Escape (Stream, Char); end Write_Char; -- ------------------------------ -- Internal method to write a character on the response stream -- and escape that character as necessary. Unlike 'Write_Char', -- this operation does not closes the current XML entity. -- ------------------------------ procedure Write_Escape (Stream : in out ResponseWriter'Class; Char : in Character) is Code : constant Unicode_Char := Character'Pos (Char); begin -- Tilde or less... -- if Code < 16#A0# then -- If "?" or over, no escaping is needed (this covers -- most of the Latin alphabet) if Code > 16#3F# or Code <= 16#20# then Stream.Write (Char); elsif Char = '<' then Stream.Write ("&lt;"); elsif Char = '>' then Stream.Write ("&gt;"); elsif Char = '&' then Stream.Write ("&amp;"); else Stream.Write (Char); end if; -- else -- declare -- S : String (1 .. 5) := "&#00;"; -- C : Unicode_Char; -- begin -- C := Code and 16#0F#; -- if C > 10 then -- S (4) := Character'Val (C - 10 + Character'Pos ('A')); -- else -- S (4) := Character'Val (C + Character'Pos ('0')); -- end if; -- C := (Code / 16) and 16#0F#; -- if C > 10 then -- S (3) := Character'Val (C - 10 + Character'Pos ('A')); -- else -- S (3) := Character'Val (C + Character'Pos ('0')); -- end if; -- Stream.Write (S); -- end; -- end if; end Write_Escape; -- ------------------------------ -- Write a character on the response stream and escape that character -- as necessary. -- ------------------------------ procedure Write_Wide_Char (Stream : in out ResponseWriter; Char : in Wide_Wide_Character) is Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char); begin Close_Current (Stream); -- Tilde or less... if Code < 16#100# then Stream.Write_Char (Character'Val (Code)); else declare S : String (1 .. 5) := "&#00;"; C : Unicode_Char; begin C := Code and 16#0F#; if C > 10 then S (4) := Character'Val (C - 10 + Character'Pos ('A')); else S (4) := Character'Val (C + Character'Pos ('0')); end if; C := (Code / 16) and 16#0F#; if C > 10 then S (3) := Character'Val (C - 10 + Character'Pos ('A')); else S (3) := Character'Val (C + Character'Pos ('0')); end if; Stream.Write (S); end; end if; end Write_Wide_Char; -- ------------------------------ -- Write a string on the stream. -- ------------------------------ procedure Write (Stream : in out ResponseWriter; Item : in Ada.Strings.Unbounded.Unbounded_String) is begin Close_Current (Stream); ASF.Streams.Print_Stream (Stream).Write (Item); end Write; end ASF.Contexts.Writer;
Write the character above 0xA0 as is. This allows to have UTF-8 sequences in a String and generate UTF-8 pages.
Write the character above 0xA0 as is. This allows to have UTF-8 sequences in a String and generate UTF-8 pages.
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8ed29ed071b54eb669f96dff9d8f99f3f3ba2977
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Doc : Wiki.Documents.Document; -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Syntax : Wiki_Syntax; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Filters : Wiki.Filters.Filter_Chain; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Doc : Wiki.Documents.Document; -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Add the plugin to the wiki engine. procedure Add_Plugin (Engine : in out Parser; Name : in String; Plugin : in Wiki.Plugins.Wiki_Plugin_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Syntax : Wiki_Syntax; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Filters : Wiki.Filters.Filter_Chain; Factory : Wiki.Plugins.Plugin_Factory_Access; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Token : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
Declare the Find function to identify a plugin instance Add a plugin factory to the Parser type
Declare the Find function to identify a plugin instance Add a plugin factory to the Parser type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e120d296f5051af8c664495b2d35fc379541741f
tools/druss-tools.adb
tools/druss-tools.adb
----------------------------------------------------------------------- -- druss-tools -- Druss main tool -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; use GNAT.Command_Line; with Ada.Command_Line; with Bbox.API; with Util.Properties; with Ada.Text_IO; with Ada.Exceptions; with Ada.Strings.Unbounded; with Util.Commands; with Util.Http.Clients.Curl; with Druss.Gateways; with Druss.Config; with Druss.Commands; procedure Druss.Tools is use Ada.Text_IO; use Ada.Strings.Unbounded; Debug : Boolean := False; Verbose : Boolean := False; List : Druss.Gateways.Gateway_Vector; First : Natural := 0; begin Druss.Commands.Initialize; Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v d e E o: t: c:") is when ASCII.NUL => exit; when 'c' => null;-- Set_Config_Directory (Parameter); when 'd' => Debug := True; when 'v' => Verbose := True; when '*' => exit; when others => null; end case; First := First + 1; end loop; Druss.Config.Initialize; Util.Http.Clients.Curl.Register; declare Cmd_Name : constant String := Full_Switch; Args : Util.Commands.Default_Argument_List (First + 1); Ctx : Druss.Commands.Context_Type; begin if Cmd_Name = "" then Druss.Commands.Driver.Usage (Args); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Druss.Config.Get_Gateways (Ctx.Gateways); Druss.Commands.Driver.Execute (Cmd_Name, Args, Ctx); end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (2); end Druss.Tools;
----------------------------------------------------------------------- -- druss-tools -- Druss main tool -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; use GNAT.Command_Line; with Ada.Command_Line; with Ada.Text_IO; with Ada.Exceptions; with Ada.Strings.Unbounded; with Util.Commands; with Util.Http.Clients.Curl; with Druss.Config; with Druss.Commands; procedure Druss.Tools is use Ada.Text_IO; use Ada.Strings.Unbounded; Config : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Strings.Unbounded.Unbounded_String; Debug : Boolean := False; Verbose : Boolean := False; First : Natural := 0; All_Args : Util.Commands.Default_Argument_List (0); begin Druss.Commands.Initialize; Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v d o: c:") is when ASCII.NUL => exit; when 'c' => Config := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'o' => Output := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'd' => Debug := True; when 'v' => Verbose := True; when '*' => exit; when others => null; end case; First := First + 1; end loop; Druss.Config.Initialize; Util.Http.Clients.Curl.Register; if First >= Ada.Command_Line.Argument_Count then Ada.Text_IO.Put_Line ("Missing command name to execute."); Druss.Commands.Driver.Usage (All_Args); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; declare Cmd_Name : constant String := Full_Switch; Args : Util.Commands.Default_Argument_List (First + 1); Ctx : Druss.Commands.Context_Type; begin Druss.Config.Get_Gateways (Ctx.Gateways); Druss.Commands.Driver.Execute (Cmd_Name, Args, Ctx); end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (2); end Druss.Tools;
Add the -o <file> and -c <file> options Fix the command execution to report usage if no command is given
Add the -o <file> and -c <file> options Fix the command execution to report usage if no command is given
Ada
apache-2.0
stcarrez/bbox-ada-api
2c26fe7c880d164d727848f5a0c60bc09eec0e94
src/asf-components-core-views.adb
src/asf-components-core-views.adb
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; package body ASF.Components.Core.Views is use ASF; use EL.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Components.Core.Views"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); end Encode_Begin; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is use type Base.UIComponent_Access; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; begin -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Begin (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- Clear the events that were queued. overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; package body ASF.Components.Core.Views is use ASF; use EL.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Components.Core.Views"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); end Encode_Begin; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is use type Base.UIComponent_Access; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; use type Base.UIComponent_Access; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then UIView'Class (Parent.all).Broadcast (Phase, Context); else -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end if; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Root.Encode_Begin (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- Clear the events that were queued. overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
Fix broadcast phase events - propagate the broadcast to the parent component until the root is reached
Fix broadcast phase events - propagate the broadcast to the parent component until the root is reached
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
039a9fdfc3008f2933b5b847423d610c22a90f16
mat/src/mat-types.adb
mat/src/mat-types.adb
----------------------------------------------------------------------- -- mat-types -- Global types -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Types is -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String is use type Interfaces.Unsigned_32; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint32 := Value; N : Uint32; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; 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 body MAT.Types is -- ------------------------------ -- Return an hexadecimal string representation of the value. -- ------------------------------ function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String is use type Interfaces.Unsigned_32; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Length) := (others => '0'); P : Uint32 := Value; N : Uint32; I : Positive := Length; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; -- ------------------------------ -- Format the target time to a printable representation. -- ------------------------------ function Tick_Image (Value : in Target_Tick_Ref) return String is use type Interfaces.Unsigned_64; Sec : Interfaces.Unsigned_32 := Interfaces.Unsigned_32 (Interfaces.Shift_Right (Value, 32)); Usec : Interfaces.Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#); begin return Interfaces.Unsigned_32'Image (Sec) & "." & Interfaces.Unsigned_32'Image (Usec); end Tick_Image; end MAT.Types;
Implement the Tick_Image procedure
Implement the Tick_Image procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
921bda608cc275e758231e67e07f82ca37d46749
src/mysql/mysql-my_list.ads
src/mysql/mysql-my_list.ads
with Interfaces.C; use Interfaces.C; with System; package Mysql.My_list is pragma Pure; -- arg-macro: function list_rest (a) -- return (a).next; -- arg-macro: function list_push (a, b) -- return a):=list_cons((b),(a); -- Copyright (C) 2000 MySQL AB -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 2 of the License. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- /usr/include/mysql/my_list.h:24:19 type st_list is record prev : access st_list; next : access st_list; data : System.Address; end record; pragma Convention (C, st_list); subtype LIST is st_list; type List_Walk_Action is access function (arg1 : System.Address; arg2 : System.Address) return int; function list_add (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_add, "list_add"); function list_delete (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_delete, "list_delete"); function list_cons (arg1 : System.Address; arg2 : access st_list) return access st_list; pragma Import (C, list_cons, "list_cons"); function list_reverse (arg1 : access st_list) return access st_list; pragma Import (C, list_reverse, "list_reverse"); procedure list_free (arg1 : access st_list; arg2 : unsigned); pragma Import (C, list_free, "list_free"); function list_length (arg1 : access st_list) return unsigned; pragma Import (C, list_length, "list_length"); end Mysql.My_list;
with Interfaces.C; use Interfaces.C; with System; package Mysql.My_list is pragma Preelaborate; -- arg-macro: function list_rest (a) -- return (a).next; -- arg-macro: function list_push (a, b) -- return a):=list_cons((b),(a); -- Copyright (C) 2000 MySQL AB -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 2 of the License. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- /usr/include/mysql/my_list.h:24:19 type st_list is record prev : access st_list; next : access st_list; data : System.Address; end record; pragma Convention (C, st_list); subtype LIST is st_list; type List_Walk_Action is access function (arg1 : System.Address; arg2 : System.Address) return int; function list_add (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_add, "list_add"); function list_delete (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_delete, "list_delete"); function list_cons (arg1 : System.Address; arg2 : access st_list) return access st_list; pragma Import (C, list_cons, "list_cons"); function list_reverse (arg1 : access st_list) return access st_list; pragma Import (C, list_reverse, "list_reverse"); procedure list_free (arg1 : access st_list; arg2 : unsigned); pragma Import (C, list_free, "list_free"); function list_length (arg1 : access st_list) return unsigned; pragma Import (C, list_length, "list_length"); end Mysql.My_list;
Change to pragma Preelaborate to avoid a Pure warning for imported functions (use of pragma Pure_Function would be incorrect for the imported functions)
Change to pragma Preelaborate to avoid a Pure warning for imported functions (use of pragma Pure_Function would be incorrect for the imported functions)
Ada
apache-2.0
stcarrez/ada-ado
749fc5ff37701e9fca481a16b96b299bcb4d68c8
src/wiki-attributes.adb
src/wiki-attributes.adb
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Unchecked_Deallocation; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Access := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List_Type; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Access := Attribute_Vectors.Element (Iter); begin if Attr.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attr); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Val : constant Wide_Wide_String := To_Wide_Wide_String (Value); Attr : constant Attribute_Access := new Attribute '(Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attr); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List_Type) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List_Type) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Attribute, Name => Attribute_Access); Item : Attribute_Access; begin while not List.List.Is_Empty loop Item := List.List.Last_Element; List.List.Delete_Last; Free (Item); end loop; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Access; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Name, Item.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List_Type) is begin List.Clear; end Finalize; end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Unchecked_Deallocation; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List_Type; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List_Type; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Val : constant Wide_Wide_String := To_Wide_Wide_String (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List_Type) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List_Type) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List_Type) is -- procedure Free is -- new Ada.Unchecked_Deallocation (Object => Attribute, -- Name => Attribute_Access); -- Item : Attribute_Access; begin -- while not List.List.Is_Empty loop -- Item := List.List.Last_Element; -- List.List.Delete_Last; -- Free (Item); -- end loop; List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List_Type) is begin List.Clear; end Finalize; end Wiki.Attributes;
Use the reference for attributes
Use the reference for attributes
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
3e7667d8190e4801909b3b63ba6c6a701a9b737b
src/wiki-attributes.ads
src/wiki-attributes.ads
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- 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; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Unbounded_Wide_Wide_String; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wide_Wide_String; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wide_Wide_String; Value : in Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wide_Wide_String (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- 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 Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Unbounded_Wide_Wide_String; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wiki.Strings.WString (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); end Wiki.Attributes;
Use the Wiki.Strings.WString type
Use the Wiki.Strings.WString type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
11273ac359e6d79c6e7efb1ede26b9bbfdd15083
awa/regtests/awa-commands-tests.ads
awa/regtests/awa-commands-tests.ads
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test start and stop command. procedure Test_Start_Stop (T : in out Test); procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); end AWA.Commands.Tests;
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test start and stop command. procedure Test_Start_Stop (T : in out Test); procedure Test_List_Tables (T : in out Test); procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); end AWA.Commands.Tests;
Declare the Test_List_Tables procedure to test the 'list -t' command
Declare the Test_List_Tables procedure to test the 'list -t' command
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
80924237ba54b37cbe9602fb29a62d97751b6993
src/asf-components.ads
src/asf-components.ads
----------------------------------------------------------------------- -- components -- Component tree -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <bASF.Components</b> describes the components that form the -- tree view. Each component has attributes and children. Children -- represent sub-components and attributes control the rendering and -- behavior of the component. -- -- The component tree is created from the <b>ASF.Views</b> tag nodes -- for each request. Unlike tag nodes, the component tree is not shared. with Ada.Strings.Unbounded; with EL.Objects; with EL.Expressions; limited with ASF.Views.Nodes; package ASF.Components is use Ada.Strings.Unbounded; -- ------------------------------ -- Attribute of a component -- ------------------------------ type UIAttribute is private; private type UIAttribute_Access is access all UIAttribute; type UIAttribute is record Definition : access ASF.Views.Nodes.Tag_Attribute; Name : Unbounded_String; Value : EL.Objects.Object; Expr : EL.Expressions.Expression; Next_Attr : UIAttribute_Access; end record; end ASF.Components;
----------------------------------------------------------------------- -- components -- Component tree -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <bASF.Components</b> describes the components that form the -- tree view. Each component has attributes and children. Children -- represent sub-components and attributes control the rendering and -- behavior of the component. -- -- The component tree is created from the <b>ASF.Views</b> tag nodes -- for each request. Unlike tag nodes, the component tree is not shared. with Ada.Strings.Unbounded; with EL.Objects; with EL.Expressions; limited with ASF.Views.Nodes; package ASF.Components is use Ada.Strings.Unbounded; -- Flag indicating whether or not this component should be rendered -- (during Render Response Phase), or processed on any subsequent form submit. -- The default value for this property is true. RENDERED_NAME : constant String := "rendered"; -- A localized user presentable name for the component. LABEL_NAME : constant String := "label"; -- Converter instance registered with the component. CONVERTER_NAME : constant String := "converter"; -- A ValueExpression enabled attribute that, if present, will be used as the text -- of the converter message, replacing any message that comes from the converter. CONVERTER_MESSAGE_NAME : constant String := "converterMessage"; -- A ValueExpression enabled attribute that, if present, will be used as the text -- of the validator message, replacing any message that comes from the validator. VALIDATOR_MESSAGE_NAME : constant String := "validatorMessage"; -- Flag indicating that the user is required to provide a submitted value for -- the input component. REQUIRED_NAME : constant String := "required"; -- A ValueExpression enabled attribute that, if present, will be used as the -- text of the validation message for the "required" facility, if the "required" -- facility is used. REQUIRED_MESSAGE_NAME : constant String := "requiredMessage"; -- ------------------------------ -- Attribute of a component -- ------------------------------ type UIAttribute is private; private type UIAttribute_Access is access all UIAttribute; type UIAttribute is record Definition : access ASF.Views.Nodes.Tag_Attribute; Name : Unbounded_String; Value : EL.Objects.Object; Expr : EL.Expressions.Expression; Next_Attr : UIAttribute_Access; end record; end ASF.Components;
Define the name of commonly used attributes
Define the name of commonly used attributes
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
d24e3d57446fbe7f686772dd76a73800295ae968
samples/serialize.adb
samples/serialize.adb
----------------------------------------------------------------------- -- serialize -- JSON serialization -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Serialize.IO.JSON; with Util.Streams.Texts; with Util.Streams.Buffered; procedure Serialize is Output : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.JSON.Output_Stream; begin Output.Initialize (Size => 10000); Stream.Initialize (Output => Output'Unchecked_Access); Stream.Start_Document; Stream.Start_Entity ("person"); Stream.Write_Entity ("name", "Harry Potter"); Stream.Write_Entity ("gender", "male"); Stream.Write_Entity ("age", 17); Stream.End_Entity ("person"); Stream.End_Document; Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Output)); end Serialize;
----------------------------------------------------------------------- -- serialize -- JSON serialization -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Serialize.IO.JSON; with Util.Streams.Texts; procedure Serialize is Output : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.JSON.Output_Stream; begin Output.Initialize (Size => 10000); Stream.Initialize (Output => Output'Unchecked_Access); Stream.Start_Document; Stream.Start_Entity ("person"); Stream.Write_Entity ("name", "Harry Potter"); Stream.Write_Entity ("gender", "male"); Stream.Write_Entity ("age", 17); Stream.End_Entity ("person"); Stream.End_Document; Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Output)); end Serialize;
Remove unecessary with clause for Util.Streams.Buffered
Remove unecessary with clause for Util.Streams.Buffered
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e223e201134ee99a44185842f8349f21c8b2bcae
regtests/security-testsuite.adb
regtests/security-testsuite.adb
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- 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 Security.OpenID.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; with Security.OAuth.JWT.Tests; package body Security.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Security.OAuth.JWT.Tests.Add_Tests (Ret); Security.OpenID.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- Copyright (C) 2011, 2012, 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.OpenID.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; with Security.OAuth.JWT.Tests; with Security.OAuth.Clients.Tests; package body Security.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Security.OAuth.JWT.Tests.Add_Tests (Ret); Security.OpenID.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); Security.OAuth.Clients.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
Add the new unit tests
Add the new unit tests
Ada
apache-2.0
stcarrez/ada-security
1fce80b396d9188bc800f698a199bf03ccb5d914
regtests/regtests.adb
regtests/regtests.adb
----------------------------------------------------------------------- -- ADO Tests -- Database sequence generator -- Copyright (C) 2009, 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Sources; with ADO.Sessions.Factory; package body Regtests is Factory : aliased ADO.Sessions.Factory.Session_Factory; Controller : aliased ADO.Sessions.Sources.Data_Source; -- ------------------------------ -- Get the database manager to be used for the unit tests -- ------------------------------ function Get_Controller return ADO.Sessions.Sources.Data_Source'Class is begin return Controller; end Get_Controller; -- ------------------------------ -- Get the readonly connection database to be used for the unit tests -- ------------------------------ function Get_Database return ADO.Sessions.Session is begin return Factory.Get_Session; end Get_Database; -- ------------------------------ -- Get the writeable connection database to be used for the unit tests -- ------------------------------ function Get_Master_Database return ADO.Sessions.Master_Session is begin return Factory.Get_Master_Session; end Get_Master_Database; -- ------------------------------ -- Initialize the test database -- ------------------------------ procedure Initialize (Name : in String) is begin Controller.Set_Connection (Name); Factory.Create (Controller); end Initialize; end Regtests;
----------------------------------------------------------------------- -- ADO Tests -- Database sequence generator -- Copyright (C) 2009, 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Factory; package body Regtests is Factory : aliased ADO.Sessions.Factory.Session_Factory; Controller : aliased ADO.Sessions.Sources.Data_Source; -- ------------------------------ -- Get the database manager to be used for the unit tests -- ------------------------------ function Get_Controller return ADO.Sessions.Sources.Data_Source'Class is begin return Controller; end Get_Controller; -- ------------------------------ -- Get the readonly connection database to be used for the unit tests -- ------------------------------ function Get_Database return ADO.Sessions.Session is begin return Factory.Get_Session; end Get_Database; -- ------------------------------ -- Get the writeable connection database to be used for the unit tests -- ------------------------------ function Get_Master_Database return ADO.Sessions.Master_Session is begin return Factory.Get_Master_Session; end Get_Master_Database; -- ------------------------------ -- Initialize the test database -- ------------------------------ procedure Initialize (Name : in String) is begin Controller.Set_Connection (Name); Factory.Create (Controller); end Initialize; end Regtests;
Fix compilation warning detected by GNAT 2017
Fix compilation warning detected by GNAT 2017
Ada
apache-2.0
stcarrez/ada-ado
5e6fca527fb7f46078ee056cbdfb8757f1d95215
src/babel_main.adb
src/babel_main.adb
with GNAT.Command_Line; use GNAT.Command_Line; with GNAT.IO; use GNAT.IO; with GNAT.Traceback.Symbolic; with Ada.Exceptions; with Ada.Command_Line; with Ada.Text_IO; with Babel; with Babel.Files; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Encoders; with Util.Encoders.Base16; with Util.Log.Loggers; with Babel.Filters; with Babel.Files.Buffers; with Babel.Files.Queues; with Babel.Stores.Local; with Babel.Strategies.Default; with Babel.Strategies.Workers; with Babel.Base.Text; with Babel.Base.Users; with Babel.Streams; with Babel.Streams.XZ; with Babel.Streams.Cached; with Babel.Streams.Files; with Tar; procedure babel_main is use Ada.Strings.Unbounded; Out_Dir : Ada.Strings.Unbounded.Unbounded_String; Dir : Babel.Files.Directory_Type; Hex_Encoder : Util.Encoders.Base16.Encoder; Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type; Local : aliased Babel.Stores.Local.Local_Store_Type; Backup : aliased Babel.Strategies.Default.Default_Strategy_Type; Buffers : aliased Babel.Files.Buffers.Buffer_Pool; Store : aliased Babel.Stores.Local.Local_Store_Type; Database : aliased Babel.Base.Text.Text_Database; Queue : aliased Babel.Files.Queues.File_Queue; Debug : Boolean := False; Task_Count : Positive := 2; -- -- procedure Print_Sha (Path : in String; -- File : in out Babel.Files.File) is -- Sha : constant String := Hex_Encoder.Transform (File.SHA1); -- begin -- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha); -- end Print_Sha; procedure Usage is begin Ada.Text_IO.Put_Line ("babel [-d] [-t count] {command} [options]"); Ada.Text_IO.Put_Line (" -d Debug mode"); Ada.Text_IO.Put_Line (" -t count Number of tasks to create"); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Commands:"); Ada.Text_IO.Put_Line (" copy <dst-dir> <src-dir>"); Ada.Text_IO.Put_Line (" scan <src-dir>"); Ada.Command_Line.Set_Exit_Status (2); end Usage; procedure Configure (Strategy : in out Babel.Strategies.Default.Default_Strategy_Type) is begin Strategy.Set_Filters (Exclude'Unchecked_Access); Strategy.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access); Strategy.Set_Buffers (Buffers'Unchecked_Access); Strategy.Set_Database (Database'Unchecked_Access); Strategy.Set_Queue (Queue'Unchecked_Access); end Configure; package Backup_Workers is new Babel.Strategies.Workers (Babel.Strategies.Default.Default_Strategy_Type); procedure Do_Backup (Count : in Positive) is Workers : Backup_Workers.Worker_Type (Count); Container : Babel.Files.Default_Container; Queue : Babel.Files.Queues.Directory_Queue; begin Babel.Files.Queues.Add_Directory (Queue, Dir); Configure (Backup); Backup_Workers.Configure (Workers, Configure'Access); Backup_Workers.Start (Workers); Backup.Scan (Queue, Container); Backup_Workers.Finish (Workers, Database); end Do_Backup; procedure Do_Copy is Dst : constant String := GNAT.Command_Line.Get_Argument; Src : constant String := GNAT.Command_Line.Get_Argument; begin Dir := Babel.Files.Allocate (Name => Src, Dir => Babel.Files.NO_DIRECTORY); -- Exclude.Add_Exclude (".svn"); -- Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 20_000_000); Store.Set_Root_Directory (Dst); Local.Set_Root_Directory (""); Store.Set_Buffers (Buffers'Unchecked_Access); Local.Set_Buffers (Buffers'Unchecked_Access); Do_Backup (Task_Count); Database.Save ("database.txt"); end Do_Copy; procedure Do_Scan is Src : constant String := GNAT.Command_Line.Get_Argument; begin Dir := Babel.Files.Allocate (Name => Src, Dir => Babel.Files.NO_DIRECTORY); Exclude.Add_Exclude (".svn"); Exclude.Add_Exclude ("obj"); Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 10, Size => 1_000_000); Local.Set_Root_Directory (Src); Do_Backup (Task_Count); Database.Save ("database.txt"); end Do_Scan; begin Util.Log.Loggers.Initialize ("babel.properties"); Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v o: t:") is when ASCII.NUL => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 'd' => Debug := True; when 't' => Task_Count := Positive'Value (Parameter); when '*' => exit; when others => null; end case; end loop; if Ada.Command_Line.Argument_Count = 0 then Usage; return; end if; declare Cmd_Name : constant String := Full_Switch; begin if Cmd_Name = "copy" then Do_Copy; elsif Cmd_Name = "scan" then Do_Scan; else Usage; end if; end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Usage; when E : others => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); Ada.Command_Line.Set_Exit_Status (1); end babel_main;
with GNAT.Command_Line; use GNAT.Command_Line; with GNAT.IO; use GNAT.IO; with GNAT.Traceback.Symbolic; with Ada.Exceptions; with Ada.Command_Line; with Ada.Text_IO; with Babel; with Babel.Files; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Encoders; with Util.Encoders.Base16; with Util.Log.Loggers; with Babel.Filters; with Babel.Files.Buffers; with Babel.Files.Queues; with Babel.Stores.Local; with Babel.Strategies.Default; with Babel.Strategies.Workers; with Babel.Base.Text; with Babel.Base.Users; with Babel.Streams; with Babel.Streams.XZ; with Babel.Streams.Cached; with Babel.Streams.Files; with Tar; procedure babel_main is use Ada.Strings.Unbounded; Out_Dir : Ada.Strings.Unbounded.Unbounded_String; Dir : Babel.Files.Directory_Type; Hex_Encoder : Util.Encoders.Base16.Encoder; Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type; Local : aliased Babel.Stores.Local.Local_Store_Type; Backup : aliased Babel.Strategies.Default.Default_Strategy_Type; Buffers : aliased Babel.Files.Buffers.Buffer_Pool; Store : aliased Babel.Stores.Local.Local_Store_Type; Database : aliased Babel.Base.Text.Text_Database; Queue : aliased Babel.Files.Queues.File_Queue; Debug : Boolean := False; Task_Count : Positive := 2; -- -- procedure Print_Sha (Path : in String; -- File : in out Babel.Files.File) is -- Sha : constant String := Hex_Encoder.Transform (File.SHA1); -- begin -- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha); -- end Print_Sha; procedure Usage is begin Ada.Text_IO.Put_Line ("babel [-d] [-t count] {command} [options]"); Ada.Text_IO.Put_Line (" -d Debug mode"); Ada.Text_IO.Put_Line (" -t count Number of tasks to create"); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Commands:"); Ada.Text_IO.Put_Line (" copy <dst-dir> <src-dir>"); Ada.Text_IO.Put_Line (" scan <src-dir>"); Ada.Command_Line.Set_Exit_Status (2); end Usage; package Backup_Workers is new Babel.Strategies.Workers (Babel.Strategies.Default.Default_Strategy_Type); procedure Do_Backup (Count : in Positive) is Workers : Backup_Workers.Worker_Type (Count); Container : Babel.Files.Default_Container; Dir_Queue : Babel.Files.Queues.Directory_Queue; procedure Configure (Strategy : in out Babel.Strategies.Default.Default_Strategy_Type) is begin Strategy.Set_Filters (Exclude'Unchecked_Access); Strategy.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access); Strategy.Set_Buffers (Buffers'Unchecked_Access); Strategy.Set_Queue (Queue'Unchecked_Access); end Configure; begin Babel.Files.Queues.Add_Directory (Dir_Queue, Dir); Configure (Backup); Backup_Workers.Configure (Workers, Configure'Access); Backup_Workers.Start (Workers); Backup.Scan (Dir_Queue, Container); Backup_Workers.Finish (Workers, Database); end Do_Backup; procedure Do_Copy is Dst : constant String := GNAT.Command_Line.Get_Argument; Src : constant String := GNAT.Command_Line.Get_Argument; begin Dir := Babel.Files.Allocate (Name => Src, Dir => Babel.Files.NO_DIRECTORY); Store.Set_Root_Directory (Dst); Local.Set_Root_Directory (""); Do_Backup (Task_Count); Database.Save ("database.txt"); end Do_Copy; procedure Do_Scan is Src : constant String := GNAT.Command_Line.Get_Argument; Workers : Backup_Workers.Worker_Type (Task_Count); Container : Babel.Files.Default_Container; Dir_Queue : Babel.Files.Queues.Directory_Queue; procedure Configure (Strategy : in out Babel.Strategies.Default.Default_Strategy_Type) is begin Strategy.Set_Filters (Exclude'Unchecked_Access); Strategy.Set_Stores (Read => Local'Unchecked_Access, Write => null); Strategy.Set_Buffers (Buffers'Unchecked_Access); Strategy.Set_Queue (Queue'Unchecked_Access); end Configure; begin Dir := Babel.Files.Allocate (Name => Src, Dir => Babel.Files.NO_DIRECTORY); Local.Set_Root_Directory (""); Babel.Files.Queues.Add_Directory (Dir_Queue, Dir); Configure (Backup); Backup_Workers.Configure (Workers, Configure'Access); Backup_Workers.Start (Workers); Backup.Scan (Dir_Queue, Container); Backup_Workers.Finish (Workers, Database); Database.Save ("database-scan.txt"); end Do_Scan; begin Util.Log.Loggers.Initialize ("babel.properties"); Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v o: t:") is when ASCII.NUL => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 'd' => Debug := True; when 't' => Task_Count := Positive'Value (Parameter); when '*' => exit; when others => null; end case; end loop; if Ada.Command_Line.Argument_Count = 0 then Usage; return; end if; Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 100, Size => 64 * 1024); Store.Set_Buffers (Buffers'Unchecked_Access); Local.Set_Buffers (Buffers'Unchecked_Access); declare Cmd_Name : constant String := Full_Switch; begin if Cmd_Name = "copy" then Do_Copy; elsif Cmd_Name = "scan" then Do_Scan; else Usage; end if; end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Usage; when E : others => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); Ada.Command_Line.Set_Exit_Status (1); end babel_main;
Update for the scan command to only scan and build the SHA1 signatures
Update for the scan command to only scan and build the SHA1 signatures
Ada
apache-2.0
stcarrez/babel
4a63297198ad93fd45c00ad2ee3b522ed21b5353
regtests/security-policies-tests.ads
regtests/security-policies-tests.ads
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Strings; with Security.Policies.Roles; package Security.Policies.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Create_Role and Get_Role_Name procedure Test_Create_Role (T : in out Test); -- Test Set_Roles procedure Test_Set_Roles (T : in out Test); -- Test Set_Roles on an invalid role name procedure Test_Set_Invalid_Roles (T : in out Test); -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. procedure Test_Get_Role_Policy (T : in out Test); -- Test Has_Permission procedure Test_Has_Permission (T : in out Test); -- Test reading an empty policy file procedure Test_Read_Empty_Policy (T : in out Test); -- Test reading policy files procedure Test_Read_Policy (T : in out Test); -- Test reading policy files and using the <role-permission> controller procedure Test_Role_Policy (T : in out Test); -- Test anonymous users and permissions. procedure Test_Anonymous_Permission (T : in out Test); -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. procedure Check_Policy (T : in out Test; File : in String; Role : in String; URL : in String; Anonymous : in Boolean := False; Granted : in Boolean := True); type Test_Principal is new Principal and Roles.Role_Principal_Context with record Name : Util.Strings.String_Ref; Roles : Security.Policies.Roles.Role_Map := (others => False); end record; -- Get the roles assigned to the user. overriding function Get_Roles (User : in Test_Principal) return Roles.Role_Map; -- Get the principal name. function Get_Name (From : in Test_Principal) return String; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- 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.Tests; with Util.Strings; with Security.Policies.Roles; package Security.Policies.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Create_Role and Get_Role_Name procedure Test_Create_Role (T : in out Test); -- Test Set_Roles procedure Test_Set_Roles (T : in out Test); -- Test Set_Roles on an invalid role name procedure Test_Set_Invalid_Roles (T : in out Test); -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. procedure Test_Get_Role_Policy (T : in out Test); -- Test Has_Permission procedure Test_Has_Permission (T : in out Test); -- Test reading an empty policy file procedure Test_Read_Empty_Policy (T : in out Test); -- Test reading policy files procedure Test_Read_Policy (T : in out Test); -- Test reading policy files and using the <role-permission> controller procedure Test_Role_Policy (T : in out Test); -- Test the Get_Grants operation. procedure Test_Grants (T : in out Test); -- Test anonymous users and permissions. procedure Test_Anonymous_Permission (T : in out Test); -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. procedure Check_Policy (T : in out Test; File : in String; Role : in String; URL : in String; Anonymous : in Boolean := False; Granted : in Boolean := True); type Test_Principal is new Principal and Roles.Role_Principal_Context with record Name : Util.Strings.String_Ref; Roles : Security.Policies.Roles.Role_Map := (others => False); end record; -- Get the roles assigned to the user. overriding function Get_Roles (User : in Test_Principal) return Roles.Role_Map; -- Get the principal name. function Get_Name (From : in Test_Principal) return String; end Security.Policies.Tests;
Declare the Test_Grants procedure
Declare the Test_Grants procedure
Ada
apache-2.0
stcarrez/ada-security
0937a1c510406b8b2dec5f992fa9a47ea745fa01
regtests/util-processes-tests.ads
regtests/util-processes-tests.ads
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2016, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Processes.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Tests when the process is not launched procedure Test_No_Process (T : in out Test); -- Test executing a process procedure Test_Spawn (T : in out Test); -- Test output pipe redirection: read the process standard output procedure Test_Output_Pipe (T : in out Test); -- Test input pipe redirection: write the process standard input procedure Test_Input_Pipe (T : in out Test); -- Test error pipe redirection: read the process standard error procedure Test_Error_Pipe (T : in out Test); -- Test shell splitting. procedure Test_Shell_Splitting_Pipe (T : in out Test); -- Test launching several processes through pipes in several threads. procedure Test_Multi_Spawn (T : in out Test); -- Test output file redirection. procedure Test_Output_Redirect (T : in out Test); -- Test input file redirection. procedure Test_Input_Redirect (T : in out Test); -- Test changing working directory. procedure Test_Set_Working_Directory (T : in out Test); -- Test various errors. procedure Test_Errors (T : in out Test); -- Test launching and stopping a process. procedure Test_Stop (T : in out Test); -- Test the Tools.Execute operation. procedure Test_Tools_Execute (T : in out Test); end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2016, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Processes.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Tests when the process is not launched procedure Test_No_Process (T : in out Test); -- Test executing a process procedure Test_Spawn (T : in out Test); -- Test output pipe redirection: read the process standard output procedure Test_Output_Pipe (T : in out Test); -- Test input pipe redirection: write the process standard input procedure Test_Input_Pipe (T : in out Test); -- Test error pipe redirection: read the process standard error procedure Test_Error_Pipe (T : in out Test); -- Test shell splitting. procedure Test_Shell_Splitting_Pipe (T : in out Test); -- Test launching several processes through pipes in several threads. procedure Test_Multi_Spawn (T : in out Test); -- Test output file redirection. procedure Test_Output_Redirect (T : in out Test); -- Test input file redirection. procedure Test_Input_Redirect (T : in out Test); -- Test changing working directory. procedure Test_Set_Working_Directory (T : in out Test); -- Test various errors. procedure Test_Errors (T : in out Test); -- Test launching and stopping a process. procedure Test_Stop (T : in out Test); -- Test various errors (pipe streams). procedure Test_Pipe_Errors (T : in out Test); -- Test launching and stopping a process (pipe streams). procedure Test_Pipe_Stop (T : in out Test); -- Test the Tools.Execute operation. procedure Test_Tools_Execute (T : in out Test); end Util.Processes.Tests;
Declare Test_Pipe_Errors and Test_Pipe_Stop procedures
Declare Test_Pipe_Errors and Test_Pipe_Stop procedures
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
34375ae1ca87233faeb645c48bfe2366f43b4c20
regtests/gen-integration-tests.ads
regtests/gen-integration-tests.ads
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- 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.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
Add new unit test to check a UML model with errors
Add new unit test to check a UML model with errors
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
783f38027616b43f9aada3b2fdee7aad69c17100
project/src/avr-usart.ads
project/src/avr-usart.ads
with System; with Ada.Unchecked_Conversion; -- ============================================================================= -- Package AVR.USART -- -- Implements Universal Asynchronous Receiver/Transmitter (UART) communication -- for the MCU micro-controller. -- ============================================================================= package AVR.USART is type USART_Control_And_Register_Status_Register_A_Type is record MPCM : Boolean; -- Multi-processor Communication Mode U2X : Boolean; -- Double the USART Transmission Speed UPE : Boolean; -- USART Parity Error DOR : Boolean; -- Data OverRun FE : Boolean; -- Frame Error UDRE : Boolean; -- USART Data Register Empty TXC : Boolean; -- USART Transmit Complete RXC : Boolean; -- USART Receive Complete end record; pragma Pack (USART_Control_And_Register_Status_Register_A_Type); for USART_Control_And_Register_Status_Register_A_Type'Size use BYTE_SIZE; type USART_Control_And_Register_Status_Register_B_Type is record TXB8 : Boolean; -- Transmit Data Bit 8 RXB8 : Boolean; -- Receive Data Bit 8 UCSZ2 : Boolean; -- Character Size Bit 2 TXEN : Boolean; -- Transmitter Enable RXEN : Boolean; -- Receiver Enable UDRIE : Boolean; -- USART Data Register Empty Interrupt Flag TXCIE : Boolean; -- Tx Complete Interrupt Flag RXCIE : Boolean; -- Rx Complete Interrupt Flag end record; pragma Pack (USART_Control_And_Register_Status_Register_B_Type); for USART_Control_And_Register_Status_Register_B_Type'Size use BYTE_SIZE; type USART_Control_And_Register_Status_Register_C_Type is record UCPOL : Boolean; -- Clock Polarity UCSZ0 : Boolean; -- Character Size Bit 0 UCSZ1 : Boolean; -- Character Size Bit 1 USBS : Boolean; -- Stop Bit Select UPM : Bit_Array_Type (0 .. 1); -- Parity Mode Bits UMSEL : Bit_Array_Type (0 .. 1); -- Mode Select end record; pragma Pack (USART_Control_And_Register_Status_Register_C_Type); for USART_Control_And_Register_Status_Register_C_Type'Size use BYTE_SIZE; type USART_Type is record UCSRA : USART_Control_And_Register_Status_Register_A_Type; UCSRB : USART_Control_And_Register_Status_Register_B_Type; UCSRC : USART_Control_And_Register_Status_Register_C_Type; Spare : Spare_Type (0 .. 7); UBRR : Byte_Array_Type (0 .. 1); -- USART Baud Rate Register L/H Bytes UDR : Byte_Type; -- USART I/O Data Register end record; pragma Pack (USART_Type); for USART_Type'Size use 7 * BYTE_SIZE; Reg_USART0 : USART_Type; for Reg_USART0'Address use System'To_Address (16#C0#); #if MCU="ATMEGA2560" then Reg_USART1 : USART_Type; for Reg_USART1'Address use System'To_Address (16#C8#); Reg_USART2 : USART_Type; for Reg_USART2'Address use System'To_Address (16#D0#); Reg_USART3 : USART_Type; for Reg_USART3'Address use System'To_Address (16#130#); #end if; -- ====================== -- General Public Section -- ====================== -- Mode of data processing type Model_Type is (POLLING, INTERRUPTIVE); -- Define the USART ports #if MCU="ATMEGA2560" then type Port_Type is (USART0, USART1, USART2, USART3); #elsif MCU="ATMEGA328P" then type Port_Type is (USART0); #end if; -- Define the USART modes type Sync_Mode_Type is (ASYNCHRONOUS, SYNCHRONOUS, MASTER_SPI); -- Define the number of bits in data communication type Data_Bits_Type is (BITS_5, BITS_6, BITS_7, BITS_8, BITS_9); for Data_Bits_Type'Size use 3; for Data_Bits_Type use (BITS_5 => 2#000#, BITS_6 => 2#001#, BITS_7 => 2#010#, BITS_8 => 2#011#, BITS_9 => 2#111#); -- Define the parity type Parity_Type is (NONE, EVEN, ODD); -- Define the number of stop bits subtype Stop_Bits_Type is Integer range 1 .. 2; -- Define the USART type for initialization type Setup_Type is record Sync_Mode : Sync_Mode_Type; Double_Speed : Boolean; Baud_Rate : Unsigned_32; Data_Bits : Data_Bits_Type; Parity : Parity_type; Stop_Bits : Stop_Bits_Type; Model : Model_Type; end record; type String_U8 is array (Unsigned_8 range <>) of Character; -- Default for USART setup #if MCU="ATMEGA2560" then USART_PORT_DEFAULT : constant Port_Type := USART0; #else USART_PORT_DEFAULT : constant Port_Type := USART0; #end if; USART_SETUP_DEFAULT : constant Setup_Type := (Sync_Mode => ASYNCHRONOUS, Double_Speed => True, Baud_Rate => 9600, Data_Bits => BITS_8, Parity => NONE, Stop_Bits => 1, Model => INTERRUPTIVE); -- To enable/disable write or receive for USART type Tx_Rx_Type is (TX, RX); -- To bufferize the Usart input type Buffer_Array_Port_Type is array (Port_Type) of Byte_Type; -- Initialize the general parameters of the USART procedure Initialize (In_Port : Port_Type; In_Setup : Setup_Type); -- ================= -- Tx Public Section -- ================= -- Transmit data over USART procedure Write (In_Port : Port_Type; In_Data : Unsigned_8); procedure Write_Char (In_Port : Port_Type; In_Data : Character); procedure Write_String_U8 (In_Port : Port_Type; In_Data : String_U8); procedure Write_Line (In_Port : Port_Type; In_Data : String_U8); procedure New_Line (In_Port : Port_Type); -- ================= -- Rx Public Section -- ================= -- Receive data from USART function Receive (In_Port : in Port_Type; Out_Data : out Unsigned_8) return Boolean; function Receive_Char (In_Port : in Port_Type; Out_Data : out Character) return Boolean; function Receive_String_U8 (In_Port : in Port_Type; Out_Data : out String_U8) return Boolean; procedure Receive_Char_Polled (In_Port : in Port_Type := USART0; Out_Data : out Character); procedure Receive_Char_Polled_Until_Flag_Char (In_Port : in AVR.USART.Port_Type; In_Char : in Character; Out_Data : out AVR.USART.String_U8); procedure Handle_ISR_RXC (In_Port : in Port_Type); function Get_Setup (In_Port : Port_Type) return Setup_Type; function To_Char is new Ada.Unchecked_Conversion (Target => Character, Source => Unsigned_8); function To_Char is new Ada.Unchecked_Conversion (Target => Character, Source => AVR.Byte_Type); function To_Unsigned_8 is new Ada.Unchecked_Conversion (Target => Unsigned_8, Source => Character); private -- ======================= -- General Private Section -- ======================= -- Used to keep the information of Usart configurations Priv_Setup : array (Port_Type) of Setup_Type; -- ================== -- Tx Private Section -- ================== -- ================== -- Rx Private Section -- ================== Priv_Receive_Buffer : Buffer_Array_Port_Type := (others => 23); Priv_Receive_Flag : array (Port_Type) of Boolean := (others => False); end AVR.USART;
with System; with Ada.Unchecked_Conversion; -- ============================================================================= -- Package AVR.USART -- -- Implements Universal Asynchronous Receiver/Transmitter (UART) communication -- for the MCU micro-controller. -- ============================================================================= package AVR.USART is type USART_Control_And_Register_Status_Register_A_Type is record MPCM : Boolean; -- Multi-processor Communication Mode U2X : Boolean; -- Double the USART Transmission Speed UPE : Boolean; -- USART Parity Error DOR : Boolean; -- Data OverRun FE : Boolean; -- Frame Error UDRE : Boolean; -- USART Data Register Empty TXC : Boolean; -- USART Transmit Complete RXC : Boolean; -- USART Receive Complete end record; pragma Pack (USART_Control_And_Register_Status_Register_A_Type); for USART_Control_And_Register_Status_Register_A_Type'Size use BYTE_SIZE; type USART_Control_And_Register_Status_Register_B_Type is record TXB8 : Boolean; -- Transmit Data Bit 8 RXB8 : Boolean; -- Receive Data Bit 8 UCSZ2 : Boolean; -- Character Size Bit 2 TXEN : Boolean; -- Transmitter Enable RXEN : Boolean; -- Receiver Enable UDRIE : Boolean; -- USART Data Register Empty Interrupt Flag TXCIE : Boolean; -- Tx Complete Interrupt Flag RXCIE : Boolean; -- Rx Complete Interrupt Flag end record; pragma Pack (USART_Control_And_Register_Status_Register_B_Type); for USART_Control_And_Register_Status_Register_B_Type'Size use BYTE_SIZE; type USART_Control_And_Register_Status_Register_C_Type is record UCPOL : Boolean; -- Clock Polarity UCSZ0 : Boolean; -- Character Size Bit 0 UCSZ1 : Boolean; -- Character Size Bit 1 USBS : Boolean; -- Stop Bit Select UPM : Bit_Array_Type (0 .. 1); -- Parity Mode Bits UMSEL : Bit_Array_Type (0 .. 1); -- Mode Select end record; pragma Pack (USART_Control_And_Register_Status_Register_C_Type); for USART_Control_And_Register_Status_Register_C_Type'Size use BYTE_SIZE; type USART_Type is record UCSRA : USART_Control_And_Register_Status_Register_A_Type; UCSRB : USART_Control_And_Register_Status_Register_B_Type; UCSRC : USART_Control_And_Register_Status_Register_C_Type; Spare : Spare_Type (0 .. 7); UBRR : Byte_Array_Type (0 .. 1); -- USART Baud Rate Register L/H Bytes UDR : Byte_Type; -- USART I/O Data Register end record; pragma Pack (USART_Type); for USART_Type'Size use 7 * BYTE_SIZE; Reg_USART0 : USART_Type; for Reg_USART0'Address use System'To_Address (16#C0#); #if MCU="ATMEGA2560" then Reg_USART1 : USART_Type; for Reg_USART1'Address use System'To_Address (16#C8#); Reg_USART2 : USART_Type; for Reg_USART2'Address use System'To_Address (16#D0#); Reg_USART3 : USART_Type; for Reg_USART3'Address use System'To_Address (16#130#); #end if; -- ====================== -- General Public Section -- ====================== -- Mode of data processing type Model_Type is (POLLING, INTERRUPTIVE); -- Define the USART ports #if MCU="ATMEGA2560" then type Port_Type is (USART0, USART1, USART2, USART3); #elsif MCU="ATMEGA328P" then type Port_Type is (USART0); #end if; -- Define the USART modes type Sync_Mode_Type is (ASYNCHRONOUS, SYNCHRONOUS, MASTER_SPI); -- Define the number of bits in data communication type Data_Bits_Type is (BITS_5, BITS_6, BITS_7, BITS_8, BITS_9); for Data_Bits_Type'Size use 3; for Data_Bits_Type use (BITS_5 => 2#000#, BITS_6 => 2#001#, BITS_7 => 2#010#, BITS_8 => 2#011#, BITS_9 => 2#111#); -- Define the parity type Parity_Type is (NONE, EVEN, ODD); -- Define the number of stop bits subtype Stop_Bits_Type is Integer range 1 .. 2; -- Define the USART type for initialization type Setup_Type is record Sync_Mode : Sync_Mode_Type; Double_Speed : Boolean; Baud_Rate : Unsigned_32; Data_Bits : Data_Bits_Type; Parity : Parity_type; Stop_Bits : Stop_Bits_Type; Model : Model_Type; end record; type String_U8 is array (Unsigned_8 range <>) of Character; -- Default for USART setup #if MCU="ATMEGA2560" then USART_PORT_DEFAULT : constant Port_Type := USART0; #else USART_PORT_DEFAULT : constant Port_Type := USART0; #end if; USART_SETUP_DEFAULT : constant Setup_Type := (Sync_Mode => ASYNCHRONOUS, Double_Speed => True, Baud_Rate => 9600, Data_Bits => BITS_8, Parity => NONE, Stop_Bits => 1, Model => POLLING); -- To enable/disable write or receive for USART type Tx_Rx_Type is (TX, RX); -- To bufferize the Usart input type Buffer_Array_Port_Type is array (Port_Type) of Byte_Type; -- Initialize the general parameters of the USART procedure Initialize (In_Port : Port_Type; In_Setup : Setup_Type); -- ================= -- Tx Public Section -- ================= -- Transmit data over USART procedure Write (In_Port : Port_Type; In_Data : Unsigned_8); procedure Write_Char (In_Port : Port_Type; In_Data : Character); procedure Write_String_U8 (In_Port : Port_Type; In_Data : String_U8); procedure Write_Line (In_Port : Port_Type; In_Data : String_U8); procedure New_Line (In_Port : Port_Type); -- ================= -- Rx Public Section -- ================= -- Receive data from USART function Receive (In_Port : in Port_Type; Out_Data : out Unsigned_8) return Boolean; function Receive_Char (In_Port : in Port_Type; Out_Data : out Character) return Boolean; function Receive_String_U8 (In_Port : in Port_Type; Out_Data : out String_U8) return Boolean; procedure Receive_Char_Polled (In_Port : in Port_Type := USART0; Out_Data : out Character); procedure Receive_Char_Polled_Until_Flag_Char (In_Port : in AVR.USART.Port_Type; In_Char : in Character; Out_Data : out AVR.USART.String_U8); procedure Handle_ISR_RXC (In_Port : in Port_Type); function Get_Setup (In_Port : Port_Type) return Setup_Type; function To_Char is new Ada.Unchecked_Conversion (Target => Character, Source => Unsigned_8); function To_Char is new Ada.Unchecked_Conversion (Target => Character, Source => AVR.Byte_Type); function To_Unsigned_8 is new Ada.Unchecked_Conversion (Target => Unsigned_8, Source => Character); private -- ======================= -- General Private Section -- ======================= -- Used to keep the information of Usart configurations Priv_Setup : array (Port_Type) of Setup_Type; -- ================== -- Tx Private Section -- ================== -- ================== -- Rx Private Section -- ================== Priv_Receive_Buffer : Buffer_Array_Port_Type := (others => 23); Priv_Receive_Flag : array (Port_Type) of Boolean := (others => False); end AVR.USART;
Change the default due to gcc bug to usart interrupt on AVR.
Change the default due to gcc bug to usart interrupt on AVR.
Ada
mit
pvrego/adaino,pvrego/adaino
913b3394b06ba2e7b7270ad35cc80bbec17935e6
src/security-auth.ads
src/security-auth.ads
----------------------------------------------------------------------- -- security-auth -- Authentication Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == Auth == -- The <b>Security.Auth</b> package implements an authentication framework that is -- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application -- to authenticate users using an external authorization server such as Google, Facebook, -- Google +, Twitter and others. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- See OpenID Connect Standard 1.0 -- http://openid.net/specs/openid-connect-standard-1_0.html -- -- See Facebook API: The Login Flow for Web (without JavaScript SDK) -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- -- Despite their subtle differences, all these authentication frameworks share almost -- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable -- for all these frameworks. -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The Authentication manager must be declared and configured. -- -- Mgr : Security.Auth.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the Auth realm and set the authentication return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify", -- Realm => "openid"); -- -- After this initialization, the authentication manager can be used in the authentication -- process. -- -- @include security-auth-openid.ads -- @include security-auth-oauth.ads -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.Auth.End_Point; -- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Credential : Security.Auth.Authentication; -- Params : Auth_Params; -- -- The auth manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Credential); -- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success. -- -- === Principal creation === -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential); -- package Security.Auth is -- Use an authentication server implementing OpenID 2.0. PROVIDER_OPENID : constant String := "openid"; -- Use the Facebook OAuth 2.0 - draft 12 authentication server. PROVIDER_FACEBOOK : constant String := "facebook"; Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- Auth provider -- ------------------------------ -- The <b>End_Point</b> represents the authentication provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The association contains the shared secret between the relying party -- and the authentication provider. The association can be cached and reused to authenticate -- different users using the same authentication provider. The association also has an -- expiration date. type Association is private; -- Get the provider. function Get_Provider (Assoc : in Association) return String; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- Authentication result -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- Authentication Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the authentication process. type Manager is tagged limited private; -- Initialize the authentication realm. procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); -- Discover the authentication 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. The discover step may do nothing for -- authentication providers based on OAuth. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the authentication provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); private use Ada.Strings.Unbounded; type Association is record Provider : Unbounded_String; Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager_Access is access all Manager'Class; type Manager is new Ada.Finalization.Limited_Controlled with record Provider : Unbounded_String; Delegate : Manager_Access; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String); end Security.Auth;
----------------------------------------------------------------------- -- security-auth -- Authentication Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == Auth == -- The <b>Security.Auth</b> package implements an authentication framework that is -- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application -- to authenticate users using an external authorization server such as Google, Facebook, -- Google +, Twitter and others. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- See OpenID Connect Standard 1.0 -- http://openid.net/specs/openid-connect-standard-1_0.html -- -- See Facebook API: The Login Flow for Web (without JavaScript SDK) -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- -- Despite their subtle differences, all these authentication frameworks share almost -- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable -- for all these frameworks. -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The Authentication manager must be declared and configured. -- -- Mgr : Security.Auth.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the Auth realm and set the authentication return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify", -- Realm => "openid"); -- -- After this initialization, the authentication manager can be used in the authentication -- process. -- -- @include security-auth-openid.ads -- @include security-auth-oauth.ads -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.Auth.End_Point; -- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Credential : Security.Auth.Authentication; -- Params : Auth_Params; -- -- The auth manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Credential); -- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success. -- -- === Principal creation === -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential); -- package Security.Auth is -- Use an authentication server implementing OpenID 2.0. PROVIDER_OPENID : constant String := "openid"; -- Use the Facebook OAuth 2.0 - draft 12 authentication server. PROVIDER_FACEBOOK : constant String := "facebook"; -- Use the Google+ OpenID Connect Basic Client PROVIDER_GOOGLE_PLUS : constant String := "google-plus"; Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- Auth provider -- ------------------------------ -- The <b>End_Point</b> represents the authentication provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The association contains the shared secret between the relying party -- and the authentication provider. The association can be cached and reused to authenticate -- different users using the same authentication provider. The association also has an -- expiration date. type Association is private; -- Get the provider. function Get_Provider (Assoc : in Association) return String; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- Authentication result -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- Authentication Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the authentication process. type Manager is tagged limited private; -- Initialize the authentication realm. procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); -- Discover the authentication 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. The discover step may do nothing for -- authentication providers based on OAuth. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the authentication provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); private use Ada.Strings.Unbounded; type Association is record Provider : Unbounded_String; Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager_Access is access all Manager'Class; type Manager is new Ada.Finalization.Limited_Controlled with record Provider : Unbounded_String; Delegate : Manager_Access; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String); end Security.Auth;
Add Google+ provider
Add Google+ provider
Ada
apache-2.0
Letractively/ada-security
04babe16ac7bee6c193e987f1c627e6c346767e1
src/mysql/ado-drivers-connections-mysql.adb
src/mysql/ado-drivers-connections-mysql.adb
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Sessions; with ADO.Statements.Mysql; with ADO.Schemas.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ overriding procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ overriding procedure Commit (Database : in out Database_Connection) is Result : char; begin if Database.Server = null then Log.Warn ("Commit while the connection is closed"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := mysql_commit (Database.Server); if Result /= nul then raise Database_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ overriding procedure Rollback (Database : in out Database_Connection) is Result : char; begin if Database.Server = null then Log.Warn ("Rollback while the connection is closed"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := mysql_rollback (Database.Server); if Result /= nul then raise Database_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Mysql.Load_Schema (Database, Schema); end Load_Schema; -- 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) is begin null; end Create_Database; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Warn ("Database connection is not open"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= null then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Get_Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Server : Mysql_Access; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), Config.Get_Server, Config.Get_Database); if Config.Get_Property ("password") = "" then Log.Debug ("MySQL connection with user={0}", Config.Get_Property ("user")); else Log.Debug ("MySQL connection with user={0} password=XXXXXXXX", Config.Get_Property ("user")); end if; Connection := mysql_init (null); Server := mysql_real_connect (Connection, ADO.C.To_C (Host), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message); mysql_close (Connection); raise ADO.Configs.Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name : in String; Item : in Util.Properties.Value); procedure Configure (Name : in String; Item : in Util.Properties.Value) is Value : constant String := Util.Properties.To_String (Item); begin if Name = "encoding" then Database.Execute ("SET NAMES " & Value); Database.Execute ("SET CHARACTER SET " & Value); Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'"); Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'"); elsif Util.Strings.Index (Name, '.') = 0 and Name /= "user" and Name /= "password" then Database.Execute ("SET " & Name & "='" & Value & "'"); end if; end Configure; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Server; Database.Name := To_Unbounded_String (Config.Get_Database); -- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands. -- Typical configuration includes: -- encoding=utf8 -- collation_connection=utf8_general_ci Config.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; end ADO.Drivers.Connections.Mysql;
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Ada.Directories; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with ADO.Sessions.Sources; with ADO.Sessions.Factory; with ADO.Statements.Mysql; with ADO.Schemas.Mysql; with ADO.Parameters; with ADO.Queries; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ overriding procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ overriding procedure Commit (Database : in out Database_Connection) is Result : char; begin if Database.Server = null then Log.Warn ("Commit while the connection is closed"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := mysql_commit (Database.Server); if Result /= nul then raise Database_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ overriding procedure Rollback (Database : in out Database_Connection) is Result : char; begin if Database.Server = null then Log.Warn ("Rollback while the connection is closed"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := mysql_rollback (Database.Server); if Result /= nul then raise Database_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Mysql.Load_Schema (Database, Schema); end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Warn ("Database connection is not open"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= null then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Get_Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Server : Mysql_Access; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), Config.Get_Server, Config.Get_Database); if Config.Get_Property ("password") = "" then Log.Debug ("MySQL connection with user={0}", Config.Get_Property ("user")); else Log.Debug ("MySQL connection with user={0} password=XXXXXXXX", Config.Get_Property ("user")); end if; Connection := mysql_init (null); Server := mysql_real_connect (Connection, ADO.C.To_C (Host), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message); mysql_close (Connection); raise ADO.Configs.Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name : in String; Item : in Util.Properties.Value); procedure Configure (Name : in String; Item : in Util.Properties.Value) is Value : constant String := Util.Properties.To_String (Item); begin if Name = "encoding" then Database.Execute ("SET NAMES " & Value); Database.Execute ("SET CHARACTER SET " & Value); Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'"); Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'"); elsif Util.Strings.Index (Name, '.') = 0 and Name /= "user" and Name /= "password" then Database.Execute ("SET " & Name & "='" & Value & "'"); end if; end Configure; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Server; Database.Name := To_Unbounded_String (Config.Get_Database); -- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands. -- Typical configuration includes: -- encoding=utf8 -- collation_connection=utf8_general_ci Config.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. -- ------------------------------ overriding procedure Create_Database (D : in out Mysql_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (D); -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. procedure Create_Mysql_Tables (Path : in String; Config : in Configs.Configuration'Class); -- Create the database identified by the given name. procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String); -- Create the user and grant him access to the database. procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String); -- ------------------------------ -- Check if the database with the given name exists. -- ------------------------------ function Has_Database (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Stmt : ADO.Statements.Query_Statement; begin Stmt := DB.Create_Statement ("SHOW DATABASES"); Stmt.Execute; while Stmt.Has_Elements loop declare D : constant String := Stmt.Get_String (0); begin if Name = D then return True; end if; end; Stmt.Next; end loop; return False; end Has_Database; -- ------------------------------ -- Check if the database with the given name has some tables. -- ------------------------------ function Has_Tables (DB : in ADO.Sessions.Session'Class; Name : in String) return Boolean is Stmt : ADO.Statements.Query_Statement; begin Stmt := DB.Create_Statement ("SHOW TABLES FROM `:name`"); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; return Stmt.Has_Elements; end Has_Tables; -- ------------------------------ -- Create the database identified by the given name. -- ------------------------------ procedure Create_Database (DB : in ADO.Sessions.Master_Session; Name : in String) is Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Creating database '{0}'", Name); Stmt := DB.Create_Statement ("CREATE DATABASE `:name`"); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Execute; end Create_Database; -- ------------------------------ -- Create the user and grant him access to the database. -- ------------------------------ procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session; Name : in String; User : in String; Password : in String) is Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name); if Password'Length > 0 then Query.Set_SQL ("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, " & "CREATE TEMPORARY TABLES, EXECUTE, SHOW VIEW ON " & "`:name`.* to `:user`@'localhost' IDENTIFIED BY :password"); else Query.Set_SQL ("GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, " & "CREATE TEMPORARY TABLES, EXECUTE, SHOW VIEW ON " & "`:name`.* to `:user`@'localhost'"); end if; Stmt := DB.Create_Statement (Query); Stmt.Bind_Param ("name", ADO.Parameters.Token (Name)); Stmt.Bind_Param ("user", ADO.Parameters.Token (User)); if Password'Length > 0 then Stmt.Bind_Param ("password", Password); end if; Stmt.Execute; Stmt := DB.Create_Statement ("FLUSH PRIVILEGES"); Stmt.Execute; end Create_User_Grant; -- ------------------------------ -- Create the MySQL tables in the database. The tables are created by launching -- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts. -- ------------------------------ procedure Create_Mysql_Tables (Path : in String; Config : in Configs.Configuration'Class) is Database : constant String := Config.Get_Database; Username : constant String := Config.Get_Property ("user"); Password : constant String := Config.Get_Property ("password"); Status : Integer; begin Log.Info ("Creating database tables using schema '{0}'", Path); if not Ada.Directories.Exists (Path) then Log.Error ("SQL file '{0}' does not exist.", Path); Log.Error ("Please, run the following command: dynamo generate db"); return; end if; if Password'Length > 0 then Util.Processes.Tools.Execute ("mysql --user='" & Username & "' --password='" & Password & "' " & Database, Path, Messages, Status); else Util.Processes.Tools.Execute ("mysql --user='" & Username & "' " & Database, Path, Messages, Status); end if; end Create_Mysql_Tables; Factory : ADO.Sessions.Factory.Session_Factory; begin Log.Info ("Connecting to {0} for database setup", Admin.Get_Log_URI); -- Initialize the session factory to connect to the -- database defined by root connection (which should allow the database creation). Factory.Create (ADO.Sessions.Sources.Data_Source (Admin)); declare DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session; begin -- Create the database only if it does not already exists. if not Has_Database (DB, Config.Get_Database) then Create_Database (DB, Config.Get_Database); end if; -- If some tables exist, don't try to create tables again. -- We could improve by reading the current database schema, comparing with our -- schema and create what is missing (new tables, new columns). if Has_Tables (DB, Config.Get_Database) then Log.Error ("The database {0} exists", Config.Get_Database); else if "" /= Config.Get_Property ("user") then -- Create the user grant. On MySQL, it is safe to do this several times. Create_User_Grant (DB, Config.Get_Database, Config.Get_Property ("user"), Config.Get_Property ("password")); end if; -- And now create the tables by using the SQL script. Create_Mysql_Tables (Schema_Path, Config); end if; end; end Create_Database; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; end ADO.Drivers.Connections.Mysql;
Implement the Create_Database (implementation moved from Dynamo create database)
Implement the Create_Database (implementation moved from Dynamo create database)
Ada
apache-2.0
stcarrez/ada-ado
cfff5fae3bc987f4cbe37e27e80e1c41052bbd12
src/natools-web-simple_pages-multipages.ads
src/natools-web-simple_pages-multipages.ads
------------------------------------------------------------------------------ -- Copyright (c) 2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Simple_Pages.Multipages extends the Simple_Pages idea by -- -- gathering several related pages into a single file, with common elements -- -- and comment parameters. -- -- The first block contains the defaults, and each of the following blocks -- -- describes a page, and unlike the Simple_Pages the first atom is not -- -- ignored, but allows to override the path rendered in -- -- templates ("Web_Path") and/or the path under which the simple page is -- -- registered ("Key_Path"), according to the following syntax: -- -- * an atom with a leading '+' has both Web_Path and Key_Path as the -- -- root multipage path followed by the suffix after '+', -- -- * an atom with a leading '-' has the Web_Path overridden by the suffix -- -- after '-' and is not registered as responding to any path in the site,-- -- * an atom with a leading '#' has the Web_Path of the root multipage -- -- followed by the suffix after '#' and is not registered in the site, -- -- * other atoms override both the Web_Path and the Key_Path. -- -- So for example, a bunch of pages can be simply merged using unprefixed -- -- atoms. A page made of several subcomponents that don't have any -- -- dedicated path but behave as self-contained entities in the rendering -- -- system can be made with the index page marked as "+" (with an empty -- -- suffix), and subcomponents as "#subanchor" so that they Web_Path still -- -- points to the relevant subcomponent. -- ------------------------------------------------------------------------------ with Natools.S_Expressions; with Natools.Web.Sites; private with Natools.S_Expressions.Atom_Refs; private with Natools.S_Expressions.Caches; package Natools.Web.Simple_Pages.Multipages is type Loader is new Sites.Page_Loader with private; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom); function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class; private type Loader is new Sites.Page_Loader with record File_Path : S_Expressions.Atom_Refs.Immutable_Reference; end record; type Default_Data is record File_Path : S_Expressions.Atom_Refs.Immutable_Reference; Elements : Containers.Expression_Maps.Constant_Map; Comment_List : S_Expressions.Caches.Cursor; Comment_Path_Prefix : S_Expressions.Atom_Refs.Immutable_Reference; Comment_Path_Suffix : S_Expressions.Atom_Refs.Immutable_Reference; end record; end Natools.Web.Simple_Pages.Multipages;
------------------------------------------------------------------------------ -- Copyright (c) 2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Simple_Pages.Multipages extends the Simple_Pages idea by -- -- gathering several related pages into a single file, with common elements -- -- and comment parameters. -- -- Each list in the input file describes a page or default values used for -- -- subsequent pages, and unlike the Simple_Pages the first atom is not -- -- ignored, but allows to override the path rendered in -- -- templates ("Web_Path") and/or the path under which the simple page is -- -- registered ("Key_Path"), according to the following syntax: -- -- * an empty atom is followed by the defaults, -- -- * an atom with a leading '+' has both Web_Path and Key_Path as the -- -- root multipage path followed by the suffix after '+', -- -- * an atom with a leading '-' has the Web_Path overridden by the suffix -- -- after '-' and is not registered as responding to any path in the site,-- -- * an atom with a leading '#' has the Web_Path of the root multipage -- -- followed by the suffix after '#' and is not registered in the site, -- -- * other atoms override both the Web_Path and the Key_Path. -- -- So for example, a bunch of pages can be simply merged using unprefixed -- -- atoms. A page made of several subcomponents that don't have any -- -- dedicated path but behave as self-contained entities in the rendering -- -- system can be made with the index page marked as "+" (with an empty -- -- suffix), and subcomponents as "#subanchor" so that they Web_Path still -- -- points to the relevant subcomponent. -- ------------------------------------------------------------------------------ with Natools.S_Expressions; with Natools.Web.Sites; private with Natools.S_Expressions.Atom_Refs; private with Natools.S_Expressions.Caches; package Natools.Web.Simple_Pages.Multipages is type Loader is new Sites.Page_Loader with private; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom); function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class; private type Loader is new Sites.Page_Loader with record File_Path : S_Expressions.Atom_Refs.Immutable_Reference; end record; type Default_Data is record File_Path : S_Expressions.Atom_Refs.Immutable_Reference; Elements : Containers.Expression_Maps.Constant_Map; Comment_List : S_Expressions.Caches.Cursor; Comment_Path_Prefix : S_Expressions.Atom_Refs.Immutable_Reference; Comment_Path_Suffix : S_Expressions.Atom_Refs.Immutable_Reference; end record; end Natools.Web.Simple_Pages.Multipages;
fix outdated description comment
simple_pages-multipages: fix outdated description comment
Ada
isc
faelys/natools-web,faelys/natools-web
144a6232489abdb280149f16e8482579e8b75968
src/ado-statements-create.ads
src/ado-statements-create.ads
----------------------------------------------------------------------- -- ADO Statements -- Database statements -- Copyright (C) 2009, 2010, 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package ADO.Statements.Create is -- Create the query statement function Create_Statement (Proxy : in Query_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Query_Statement; -- Create the delete statement function Create_Statement (Proxy : in Delete_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Delete_Statement; -- Create an update statement function Create_Statement (Proxy : in Update_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Update_Statement; -- Create the insert statement. function Create_Statement (Proxy : in Update_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Insert_Statement; end ADO.Statements.Create;
----------------------------------------------------------------------- -- ADO Statements -- Database statements -- Copyright (C) 2009, 2010, 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package ADO.Statements.Create is -- Create the query statement function Create_Statement (Proxy : in Query_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Query_Statement; -- Create the delete statement function Create_Statement (Proxy : in Delete_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Delete_Statement; -- Create an update statement function Create_Statement (Proxy : in Update_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Update_Statement; -- Create the insert statement. function Create_Statement (Proxy : in Update_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Insert_Statement; end ADO.Statements.Create;
Fix style compilation warning
Fix style compilation warning
Ada
apache-2.0
stcarrez/ada-ado
d83fa05862d9ce37bffebc2fe0fbb0e6f2316988
test/src/nls_test.adb
test/src/nls_test.adb
------------------------------------------------------------------------------ -- -- -- Copyright (c) 2014-2022 Vitalii Bondarenko <[email protected]> -- -- -- ------------------------------------------------------------------------------ -- -- -- The MIT License (MIT) -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, sublicense, and/or sell copies of the Software, and to -- -- permit persons to whom the Software is furnished to do so, subject to -- -- the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Text_IO; use Ada.Strings.Unbounded.Text_IO; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings; with L10n; use L10n; with L10n.Langinfo; use L10n.Langinfo; with L10n.Localeinfo; use L10n.Localeinfo; with I18n; use I18n; procedure NLS_Test is package Enum_IO is new Ada.Text_IO.Enumeration_IO (Locale_Item); ----------------- -- Print_Lconv -- ----------------- procedure Print_Lconv is Lconv : Lconv_Access; begin Lconv := Localeconv; Put_Line ("Localeconv Result"); Put_Line ("-----------------"); Put_Line (-"Decimal Point : '" & Lconv.Decimal_Point & "'"); Put_Line (-"Thousands Separator : '" & Lconv.Thousands_Sep & "'"); Put_Line (-"Grouping Format : '" & Lconv.Grouping & "'"); Put_Line (-"Int'l Currency Symbol : '" & Lconv.Int_Curr_Symbol & "'"); Put_Line (-"Local Currency Symbol : '" & Lconv.Currency_Symbol & "'"); Put_Line (-"Monetary Decimal Point : '" & Lconv.Mon_Decimal_Point & "'"); Put_Line (-"Monetary Thousands Separator : '" & Lconv.Mon_Thousands_Sep & "'"); Put_Line (-"Monetary Grouping Format : '" & Lconv.Mon_Grouping & "'"); Put_Line (-"Positive Sign : '" & Lconv.Positive_Sign & "'"); Put_Line (-"Negative Sign : '" & Lconv.Negative_Sign & "'"); Put_Line (-"Int'l Fraction Digits : '" & Lconv.Int_Frac_Digits'Img & "'"); Put_Line (-"Local Fraction Digits : '" & Lconv.Frac_Digits'Img & "'"); Put_Line (-"P_Cs_Precedes : '" & Lconv.P_Cs_Precedes'Img & "'"); Put_Line (-"P_Sep_By_Space : '" & Lconv.P_Sep_By_Space'Img & "'"); Put_Line (-"N_Cs_Precedes : '" & Lconv.N_Cs_Precedes'Img & "'"); Put_Line (-"N_Sep_By_Space : '" & Lconv.N_Sep_By_Space'Img & "'"); Put_Line (-"Positive sign positions : '" & Lconv.P_Sign_Posn'Img & "'"); Put_Line (-"Negative sign positions : '" & Lconv.N_Sign_Posn'Img & "'"); Put_Line (-"Int_P_Cs_Precedes : '" & Lconv.Int_P_Cs_Precedes'Img & "'"); Put_Line (-"Int_P_Sep_By_Space : '" & Lconv.Int_P_Sep_By_Space'Img & "'"); Put_Line (-"Int_N_Cs_Precedes : '" & Lconv.Int_N_Cs_Precedes'Img & "'"); Put_Line (-"Int_N_Sep_By_Space : '" & Lconv.Int_N_Sep_By_Space'Img & "'"); Put_Line (-"Int'l Positive sign positions : '" & Lconv.Int_P_Sign_Posn'Img & "'"); Put_Line (-"Int'l Negative sign positions : '" & Lconv.Int_N_Sign_Posn'Img & "'"); end Print_Lconv; ----------------------- -- Print_Nl_Langinfo -- ----------------------- procedure Print_Nl_Langinfo is begin Put_Line ("Nl_Langinfo Result"); Put_Line ("------------------"); for Item in Locale_Item'Range loop Enum_IO.Put (Item); Put (" : "); Put_Line ("'" & Nl_Langinfo (Item) & "'"); end loop; end Print_Nl_Langinfo; begin Set_Locale; Text_Domain ("nls_test"); Bind_Text_Domain ("nls_test", ""); -- POSIX format locale name string -- Set_Locale (Locale => "C"); Set_Locale (Locale => "uk_UA.UTF-8"); -- Windows format locale name string -- Set_Locale (Locale => "Ukrainian_Ukraine.1251"); Put_Line (-"Current locale : " & Get_Locale); New_Line; Print_Lconv; New_Line; Print_Nl_Langinfo; end NLS_Test;
------------------------------------------------------------------------------ -- -- -- Copyright (c) 2014-2022 Vitalii Bondarenko <[email protected]> -- -- -- ------------------------------------------------------------------------------ -- -- -- The MIT License (MIT) -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, sublicense, and/or sell copies of the Software, and to -- -- permit persons to whom the Software is furnished to do so, subject to -- -- the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Text_IO; use Ada.Strings.Unbounded.Text_IO; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings; with L10n; use L10n; with L10n.Langinfo; use L10n.Langinfo; with L10n.Localeinfo; use L10n.Localeinfo; with I18n; use I18n; procedure NLS_Test is package Enum_IO is new Ada.Text_IO.Enumeration_IO (Locale_Item); ----------------- -- Print_Lconv -- ----------------- procedure Print_Lconv is Lconv : Lconv_Access; begin Lconv := Localeconv; Put_Line ("Localeconv Result"); Put_Line ("-----------------"); Put_Line (-"Decimal Point : '" & Lconv.Decimal_Point & "'"); Put_Line (-"Thousands Separator : '" & Lconv.Thousands_Sep & "'"); Put_Line (-"Grouping Format : '" & Lconv.Grouping & "'"); Put_Line (-"Int'l Currency Symbol : '" & Lconv.Int_Curr_Symbol & "'"); Put_Line (-"Local Currency Symbol : '" & Lconv.Currency_Symbol & "'"); Put_Line (-"Monetary Decimal Point : '" & Lconv.Mon_Decimal_Point & "'"); Put_Line (-"Monetary Thousands Separator : '" & Lconv.Mon_Thousands_Sep & "'"); Put_Line (-"Monetary Grouping Format : '" & Lconv.Mon_Grouping & "'"); Put_Line (-"Positive Sign : '" & Lconv.Positive_Sign & "'"); Put_Line (-"Negative Sign : '" & Lconv.Negative_Sign & "'"); Put_Line (-"Int'l Fraction Digits : '" & Lconv.Int_Frac_Digits'Img & "'"); Put_Line (-"Local Fraction Digits : '" & Lconv.Frac_Digits'Img & "'"); Put_Line (-"P_Cs_Precedes : '" & Lconv.P_Cs_Precedes'Img & "'"); Put_Line (-"P_Sep_By_Space : '" & Lconv.P_Sep_By_Space'Img & "'"); Put_Line (-"N_Cs_Precedes : '" & Lconv.N_Cs_Precedes'Img & "'"); Put_Line (-"N_Sep_By_Space : '" & Lconv.N_Sep_By_Space'Img & "'"); Put_Line (-"Positive sign positions : '" & Lconv.P_Sign_Posn'Img & "'"); Put_Line (-"Negative sign positions : '" & Lconv.N_Sign_Posn'Img & "'"); Put_Line (-"Int_P_Cs_Precedes : '" & Lconv.Int_P_Cs_Precedes'Img & "'"); Put_Line (-"Int_P_Sep_By_Space : '" & Lconv.Int_P_Sep_By_Space'Img & "'"); Put_Line (-"Int_N_Cs_Precedes : '" & Lconv.Int_N_Cs_Precedes'Img & "'"); Put_Line (-"Int_N_Sep_By_Space : '" & Lconv.Int_N_Sep_By_Space'Img & "'"); Put_Line (-"Int'l Positive sign positions : '" & Lconv.Int_P_Sign_Posn'Img & "'"); Put_Line (-"Int'l Negative sign positions : '" & Lconv.Int_N_Sign_Posn'Img & "'"); end Print_Lconv; ----------------------- -- Print_Nl_Langinfo -- ----------------------- procedure Print_Nl_Langinfo is begin Put_Line ("Nl_Langinfo Result"); Put_Line ("------------------"); for Item in Locale_Item'Range loop Enum_IO.Put (Item); Put (" : "); Put_Line ("'" & Nl_Langinfo (Item) & "'"); end loop; end Print_Nl_Langinfo; begin Set_Locale; Text_Domain ("nls_test"); Bind_Text_Domain ("nls_test", ""); -- POSIX format locale name string -- Set_Locale (Locale => "C"); -- Set_Locale (Locale => "uk_UA.UTF-8"); -- Windows format locale name string -- Set_Locale (Locale => "Ukrainian_Ukraine.1251"); Put_Line (-"Current locale : " & Get_Locale); New_Line; Print_Lconv; New_Line; Print_Nl_Langinfo; end NLS_Test;
Test change
Test change
Ada
mit
VitalijBondarenko/adanls
a47b6da89b6fa60d15aa1308ec0d7270cf022893
src/xml/util-serialize-io-xml.ads
src/xml/util-serialize-io-xml.ads
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- Copyright (C) 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Streams.Texts; package Util.Serialize.IO.XML is Parse_Error : exception; type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class); -- Set the XHTML reader to ignore or not the white spaces. -- When set to True, the ignorable white spaces will not be kept. procedure Set_Ignore_White_Spaces (Reader : in out Parser; Value : in Boolean); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; type Xhtml_Reader is new Sax.Readers.Reader with private; -- ------------------------------ -- XML Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating an XML output stream. -- The stream object takes care of the XML escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Write a character on the response stream and escape that character as necessary. procedure Write_Escape (Stream : in out Output_Stream'Class; Char : in Wide_Wide_Character); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new XML object. procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current XML object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a XML name/value attribute. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Write a XML name/value entity (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Starts a XML array. overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a XML array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); -- Return the location where the exception was raised. function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class) return String; private overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); overriding procedure Start_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""; Atts : in Sax.Attributes.Attributes'Class); overriding procedure End_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); overriding function Resolve_Entity (Handler : Xhtml_Reader; Public_Id : Unicode.CES.Byte_Sequence; System_Id : Unicode.CES.Byte_Sequence) return Input_Sources.Input_Source_Access; overriding procedure Start_DTD (Handler : in out Xhtml_Reader; Name : Unicode.CES.Byte_Sequence; Public_Id : Unicode.CES.Byte_Sequence := ""; System_Id : Unicode.CES.Byte_Sequence := ""); procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence); type Xhtml_Reader is new Sax.Readers.Reader with record Stack_Pos : Natural := 0; Handler : access Parser'Class; Text : Ada.Strings.Unbounded.Unbounded_String; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; Sink : access Reader'Class; end record; type Parser is new Util.Serialize.IO.Parser with record -- The SAX locator to find the current file and line number. Locator : Sax.Locators.Locator; Has_Pending_Char : Boolean := False; Pending_Char : Character; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Close_Start : Boolean := False; Stream : Util.Streams.Texts.Print_Stream_Access; end record; end Util.Serialize.IO.XML;
----------------------------------------------------------------------- -- util-serialize-io-xml -- XML Serialization Driver -- Copyright (C) 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sax.Exceptions; with Sax.Locators; with Sax.Readers; with Sax.Attributes; with Unicode.CES; with Input_Sources; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Streams.Buffered; with Util.Streams.Texts; package Util.Serialize.IO.XML is Parse_Error : exception; type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class); -- Set the XHTML reader to ignore or not the white spaces. -- When set to True, the ignorable white spaces will not be kept. procedure Set_Ignore_White_Spaces (Reader : in out Parser; Value : in Boolean); -- Set the XHTML reader to ignore empty lines. procedure Set_Ignore_Empty_Lines (Reader : in out Parser; Value : in Boolean); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; type Xhtml_Reader is new Sax.Readers.Reader with private; -- ------------------------------ -- XML Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating an XML output stream. -- The stream object takes care of the XML escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Write a character on the response stream and escape that character as necessary. procedure Write_Escape (Stream : in out Output_Stream'Class; Char : in Wide_Wide_Character); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Write the value as a XML string. Special characters are escaped using the XML -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new XML object. procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current XML object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a XML name/value attribute. procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Nullables.Nullable_String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Write a XML name/value entity (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Starts a XML array. overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a XML array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); -- Return the location where the exception was raised. function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class) return String; private overriding procedure Warning (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Fatal_Error (Handler : in out Xhtml_Reader; Except : in Sax.Exceptions.Sax_Parse_Exception'Class); overriding procedure Set_Document_Locator (Handler : in out Xhtml_Reader; Loc : in out Sax.Locators.Locator); overriding procedure Start_Document (Handler : in out Xhtml_Reader); overriding procedure End_Document (Handler : in out Xhtml_Reader); overriding procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence; URI : in Unicode.CES.Byte_Sequence); overriding procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader; Prefix : in Unicode.CES.Byte_Sequence); overriding procedure Start_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""; Atts : in Sax.Attributes.Attributes'Class); overriding procedure End_Element (Handler : in out Xhtml_Reader; Namespace_URI : in Unicode.CES.Byte_Sequence := ""; Local_Name : in Unicode.CES.Byte_Sequence := ""; Qname : in Unicode.CES.Byte_Sequence := ""); overriding procedure Characters (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader; Ch : in Unicode.CES.Byte_Sequence); overriding procedure Processing_Instruction (Handler : in out Xhtml_Reader; Target : in Unicode.CES.Byte_Sequence; Data : in Unicode.CES.Byte_Sequence); overriding procedure Skipped_Entity (Handler : in out Xhtml_Reader; Name : in Unicode.CES.Byte_Sequence); overriding procedure Start_Cdata (Handler : in out Xhtml_Reader); overriding procedure End_Cdata (Handler : in out Xhtml_Reader); overriding function Resolve_Entity (Handler : Xhtml_Reader; Public_Id : Unicode.CES.Byte_Sequence; System_Id : Unicode.CES.Byte_Sequence) return Input_Sources.Input_Source_Access; overriding procedure Start_DTD (Handler : in out Xhtml_Reader; Name : Unicode.CES.Byte_Sequence; Public_Id : Unicode.CES.Byte_Sequence := ""; System_Id : Unicode.CES.Byte_Sequence := ""); procedure Collect_Text (Handler : in out Xhtml_Reader; Content : Unicode.CES.Byte_Sequence); type Xhtml_Reader is new Sax.Readers.Reader with record Stack_Pos : Natural := 0; Handler : access Parser'Class; Text : Ada.Strings.Unbounded.Unbounded_String; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; Sink : access Reader'Class; end record; type Parser is new Util.Serialize.IO.Parser with record -- The SAX locator to find the current file and line number. Locator : Sax.Locators.Locator; Has_Pending_Char : Boolean := False; Pending_Char : Character; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Close_Start : Boolean := False; Stream : Util.Streams.Texts.Print_Stream_Access; end record; end Util.Serialize.IO.XML;
Declare Write_Attribute and Write_Entity for Nullable_String
Declare Write_Attribute and Write_Entity for Nullable_String
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3fc3346d265ff8701f7e7f2d4eed606cdbcda39b
mat/src/mat-readers.adb
mat/src/mat-readers.adb
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Events; with MAT.Types; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers"); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Attribute_Table_Ptr) is Handler : Message_Handler; begin Handler.For_Servant := Reader; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Readers.Insert (Name, Handler); end Register_Reader; procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message) is Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else declare Handler : constant Message_Handler := Handler_Maps.Element (Pos); begin Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg); end; end if; end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name); procedure Read_Attributes (Key : in String; Element : in out Message_Handler) is begin Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); begin for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); end if; end loop; end; end loop; end Read_Attributes; begin Log.Debug ("Read event definition {0}", Name); if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Read_Attributes'Access); end if; end Read_Definition; procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message) is Count : MAT.Types.Uint16; begin Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Client.Flags := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; end Read_Headers; end MAT.Readers;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Events; with MAT.Types; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers"); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Message_Handler; begin Handler.For_Servant := Reader; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Readers.Insert (Name, Handler); end Register_Reader; procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message) is Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else declare Handler : constant Message_Handler := Handler_Maps.Element (Pos); begin Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg); end; end if; end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name); procedure Read_Attributes (Key : in String; Element : in out Message_Handler) is begin Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); begin for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); end if; end loop; end; end loop; end Read_Attributes; begin Log.Debug ("Read event definition {0}", Name); if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Read_Attributes'Access); end if; end Read_Definition; procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message) is Count : MAT.Types.Uint16; begin Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Client.Flags := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; end Read_Headers; end MAT.Readers;
Use a Const_Attribute_Table_Access for the model
Use a Const_Attribute_Table_Access for the model
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d3e59360df9ce773c84f2f8d8baf638c63bc50e1
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; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; 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 private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. 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; type Target_Type is tagged limited record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; end record; 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; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; 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 private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. 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; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is tagged limited record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; end record; end MAT.Targets;
Store the path in the Target_Process
Store the path in the Target_Process
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b8d7d643abcda9ec7e7edb69831b1cbcb7a45459
src/asf-components-utils-beans.adb
src/asf-components-utils-beans.adb
----------------------------------------------------------------------- -- components-utils-beans -- Bean component utility -- 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 body ASF.Components.Utils.Beans is -- ------------------------------ -- Evaluate the <b>value</b> attribute and set it in the value expression -- referred to by the <b>var</b> attribute. -- ------------------------------ overriding procedure Encode_Begin (UI : in UISetBean; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is VE : constant EL.Expressions.Value_Expression := UI.Get_Value_Expression ("var"); begin if VE.Is_Null then UI.Log_Error ("Invalid value expression for 'var'"); return; end if; VE.Set_Value (Context => Context.Get_ELContext.all, Value => UI.Get_Attribute (Context => Context, Name => "value")); end Encode_Begin; end ASF.Components.Utils.Beans;
----------------------------------------------------------------------- -- components-utils-beans -- Bean component utility -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; package body ASF.Components.Utils.Beans is -- ------------------------------ -- Evaluate the <b>value</b> attribute and set it in the value expression -- referred to by the <b>var</b> attribute. -- ------------------------------ overriding procedure Encode_Begin (UI : in UISetBean; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Name : constant String := Util.Beans.Objects.To_String (UI.Get_Attribute (Context, "var")); begin if Name'Length > 0 then Context.Set_Attribute (Name, UI.Get_Attribute (Context => Context, Name => "value")); else declare VE : constant EL.Expressions.Value_Expression := UI.Get_Value_Expression ("var"); begin if VE.Is_Null then UI.Log_Error ("Invalid value expression for 'var'"); return; end if; VE.Set_Value (Context => Context.Get_ELContext.all, Value => UI.Get_Attribute (Context => Context, Name => "value")); end; end if; end Encode_Begin; end ASF.Components.Utils.Beans;
Fix the <util:set> component to set a variable or a bean attribute
Fix the <util:set> component to set a variable or a bean attribute
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6c360576657e4af1eae2e4b408977466c7c254ba
src/security-contexts.adb
src/security-contexts.adb
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Unchecked_Deallocation; package body Security.Contexts is use type Security.Policies.Policy_Context_Array_Access; use type Security.Policies.Policy_Access; use type Security.Policies.Policy_Context_Access; package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context'Class, Name => Security.Policies.Policy_Context_Access); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return null; else return Context.Manager.Get_Policy (Name); end if; end Get_Policy; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- Returns True if the permission is granted. -- ------------------------------ function Has_Permission (Context : in Security_Context; Permission : in Permissions.Permission_Index) return Boolean is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return False; end if; declare Perm : Security.Permissions.Permission (Permission); begin return Context.Manager.Has_Permission (Context, Perm); end; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- Returns True if the permission is granted. -- ------------------------------ function Has_Permission (Context : in Security_Context; Permission : in String) return Boolean is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin return Security_Context'Class (Context).Has_Permission (Index); end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- Returns True if the permission is granted. -- ------------------------------ function Has_Permission (Context : in Security_Context; Permission : in Permissions.Permission'Class) return Boolean is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return False; else return Context.Manager.Has_Permission (Context, Permission); end if; end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context_Array, Name => Security.Policies.Policy_Context_Array_Access); begin Task_Context.Set_Value (Context.Previous); if Context.Contexts /= null then for I in Context.Contexts'Range loop Free (Context.Contexts (I)); end loop; Free (Context.Contexts); end if; end Finalize; -- ------------------------------ -- Set a policy context information represented by <b>Value</b> and associated with -- the policy index <b>Policy</b>. -- ------------------------------ procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access) is begin if Context.Contexts = null then Context.Contexts := Context.Manager.Create_Policy_Contexts; end if; Free (Context.Contexts (Policy.Get_Policy_Index)); Context.Contexts (Policy.Get_Policy_Index) := Value; end Set_Policy_Context; -- ------------------------------ -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. -- ------------------------------ function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access is Result : Security.Policies.Policy_Context_Access; begin if Policy = null then raise Invalid_Policy; end if; if Context.Contexts = null then raise Invalid_Context; end if; Result := Context.Contexts (Policy.Get_Policy_Index); return Result; end Get_Policy_Context; -- ------------------------------ -- Returns True if a context information was registered for the security policy. -- ------------------------------ function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean is begin return Policy /= null and then Context.Contexts /= null and then Context.Contexts (Policy.Get_Policy_Index) /= null; end Has_Policy_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Context : constant Security_Context_Access := Current; begin if Context = null then return False; else return Context.Has_Permission (Permission); end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- ------------------------------ function Has_Permission (Permission : in String) return Boolean is Context : constant Security_Context_Access := Current; begin if Context = null then return False; else return Context.Has_Permission (Permission); end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission'Class) return Boolean is Context : constant Security_Context_Access := Current; begin if Context = null then return False; else return Context.Has_Permission (Permission); end if; end Has_Permission; end Security.Contexts;
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Unchecked_Deallocation; package body Security.Contexts is use type Security.Policies.Policy_Context_Array_Access; use type Security.Policies.Policy_Access; use type Security.Policies.Policy_Context_Access; package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context'Class, Name => Security.Policies.Policy_Context_Access); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return null; else return Context.Manager.Get_Policy (Name); end if; end Get_Policy; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- Returns True if the permission is granted. -- ------------------------------ function Has_Permission (Context : in Security_Context; Permission : in Permissions.Permission_Index) return Boolean is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return False; end if; declare Perm : Security.Permissions.Permission (Permission); begin return Context.Manager.Has_Permission (Context, Perm); end; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- Returns True if the permission is granted. -- ------------------------------ function Has_Permission (Context : in Security_Context; Permission : in String) return Boolean is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin return Security_Context'Class (Context).Has_Permission (Index); end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- Returns True if the permission is granted. -- ------------------------------ function Has_Permission (Context : in Security_Context; Permission : in Permissions.Permission'Class) return Boolean is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return False; else return Context.Manager.Has_Permission (Context, Permission); end if; end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; -- If we already have a security context, setup the manager and user principal. if Context.Previous /= null then Context.Manager := Context.Previous.Manager; Context.Principal := Context.Previous.Principal; end if; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context_Array, Name => Security.Policies.Policy_Context_Array_Access); begin Task_Context.Set_Value (Context.Previous); if Context.Contexts /= null then for I in Context.Contexts'Range loop Free (Context.Contexts (I)); end loop; Free (Context.Contexts); end if; end Finalize; -- ------------------------------ -- Set a policy context information represented by <b>Value</b> and associated with -- the policy index <b>Policy</b>. -- ------------------------------ procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access) is begin if Context.Contexts = null then Context.Contexts := Context.Manager.Create_Policy_Contexts; end if; Free (Context.Contexts (Policy.Get_Policy_Index)); Context.Contexts (Policy.Get_Policy_Index) := Value; end Set_Policy_Context; -- ------------------------------ -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. -- ------------------------------ function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access is Result : Security.Policies.Policy_Context_Access; begin if Policy = null then raise Invalid_Policy; end if; if Context.Contexts = null then raise Invalid_Context; end if; Result := Context.Contexts (Policy.Get_Policy_Index); return Result; end Get_Policy_Context; -- ------------------------------ -- Returns True if a context information was registered for the security policy. -- ------------------------------ function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean is begin return Policy /= null and then Context.Contexts /= null and then Context.Contexts (Policy.Get_Policy_Index) /= null; end Has_Policy_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access) is use type Security.Policies.Policy_Manager_Access; use type Security.Principal_Access; begin if Manager /= null then Context.Manager := Manager; end if; if Principal /= null then Context.Principal := Principal; end if; if Manager = null and Principal = null then raise Invalid_Context with "There is no policy manager and no user principal"; end if; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Context : constant Security_Context_Access := Current; begin if Context = null then return False; else return Context.Has_Permission (Permission); end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- ------------------------------ function Has_Permission (Permission : in String) return Boolean is Context : constant Security_Context_Access := Current; begin if Context = null then return False; else return Context.Has_Permission (Permission); end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission'Class) return Boolean is Context : constant Security_Context_Access := Current; begin if Context = null then return False; else return Context.Has_Permission (Permission); end if; end Has_Permission; end Security.Contexts;
Fix Set_Context and Initialize to track nested security contexts
Fix Set_Context and Initialize to track nested security contexts
Ada
apache-2.0
stcarrez/ada-security
6b688a2a54adc98e3708380f7de4800f8b206990
tools/druss-commands-bboxes.adb
tools/druss-commands-bboxes.adb
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with Druss.Config; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); procedure Discover (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Discover; -- Add the bbox with the given IP address. procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP); begin if not Gw.Is_Null then Log.Debug ("Bbox {0} is already registered", IP); return; end if; Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a new bbox at {0}", IP); Gw := Druss.Gateways.Gateway_Refs.Create; Gw.Value.IP := Ada.Strings.Unbounded.To_Unbounded_String (IP); Context.Gateways.Append (Gw); end if; exception when E : others => null; end Add_Bbox; procedure Discover (Command : in Command_Type; Context : in out Context_Type) is Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Check_Bbox (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Check_Bbox; procedure Process (URI : in String) is Pos : Natural; begin if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then return; end if; Pos := Util.Strings.Index (URI, ':', 6); if Pos > 0 then Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context); -- Check_Bbox (); end if; end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; Druss.Config.Save_Gateways (Context.Gateways); end Discover; -- ------------------------------ -- Set the password to be used by the Bbox API to connect to the box. -- ------------------------------ procedure Password (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count < 2 then Druss.Commands.Driver.Usage (Args); end if; declare Passwd : constant String := Args.Get_Argument (2); Gw : Druss.Gateways.Gateway_Ref; procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd); end Change_Password; begin if Args.Get_Count = 2 then Druss.Gateways.Iterate (Context.Gateways, Change_Password'Access); else for I in 3 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Change_Password (Gw.Value.all); end if; end loop; end if; Druss.Config.Save_Gateways (Context.Gateways); end; end Password; -- ------------------------------ -- 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 Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover (Context); elsif Args.Get_Argument (1) = "password" then Command.Password (Args, Context); else Put_Line ("Invalid sub-command: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Manage and define the configuration to connect to the Bbox"); Put_Line ("Usage: bbox <operation>..."); New_Line; Put_Line (" Druss needs to know the list of Bboxes which are available on the network."); Put_Line (" It also need some credentials to connect to the Bbox using the Bbox API."); Put_Line (" The 'bbox' command allows to manage that list and configuration."); Put_Line (" Examples:"); Put_Line (" bbox discover Discover the bbox(es) connected to the LAN"); Put_Line (" bbox add IP Add a bbox knowing its IP address"); Put_Line (" bbox del IP Delete a bbox from the list"); Put_Line (" bbox password <pass> [IP] Set the bbox API connection password"); end Help; 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. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with Druss.Config; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); procedure Discover (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Discover; -- Add the bbox with the given IP address. procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP); begin if not Gw.Is_Null then Log.Debug ("Bbox {0} is already registered", IP); return; end if; Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a new bbox at {0}", IP); Gw := Druss.Gateways.Gateway_Refs.Create; Gw.Value.IP := Ada.Strings.Unbounded.To_Unbounded_String (IP); Context.Gateways.Append (Gw); end if; exception when E : others => null; end Add_Bbox; procedure Discover (Command : in Command_Type; Context : in out Context_Type) is Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Check_Bbox (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Check_Bbox; procedure Process (URI : in String) is Pos : Natural; begin if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then return; end if; Pos := Util.Strings.Index (URI, ':', 6); if Pos > 0 then Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context); -- Check_Bbox (); end if; end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; Druss.Config.Save_Gateways (Context.Gateways); end Discover; -- ------------------------------ -- Set the password to be used by the Bbox API to connect to the box. -- ------------------------------ procedure Password (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type; Passwd : in String) is begin Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd); end Change_Password; begin Druss.Commands.Gateway_Command (Command, Args, 2, Change_Password'Access, Context); Druss.Config.Save_Gateways (Context.Gateways); end Password; -- ------------------------------ -- 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 Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover (Context); elsif Args.Get_Argument (1) = "password" then Command.Password (Args, Context); else Put_Line ("Invalid sub-command: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Manage and define the configuration to connect to the Bbox"); Put_Line ("Usage: bbox <operation>..."); New_Line; Put_Line (" Druss needs to know the list of Bboxes which are available on the network."); Put_Line (" It also need some credentials to connect to the Bbox using the Bbox API."); Put_Line (" The 'bbox' command allows to manage that list and configuration."); Put_Line (" Examples:"); Put_Line (" bbox discover Discover the bbox(es) connected to the LAN"); Put_Line (" bbox add IP Add a bbox knowing its IP address"); Put_Line (" bbox del IP Delete a bbox from the list"); Put_Line (" bbox password <pass> [IP] Set the bbox API connection password"); end Help; end Druss.Commands.Bboxes;
Use the Gateway_Command procedure for the password command
Use the Gateway_Command procedure for the password command
Ada
apache-2.0
stcarrez/bbox-ada-api
b592973620f8154ed16a3c380009ac108d6a6c63
arch/ARM/Nordic/devices/nrf52/nrf-device.ads
arch/ARM/Nordic/devices/nrf52/nrf-device.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016-2020, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with nRF.GPIO; use nRF.GPIO; with nRF.RTC; use nRF.RTC; with NRF_SVD.RTC; with nRF.TWI; use nRF.TWI; with NRF_SVD.TWI; with nRF.SPI_Master; use nRF.SPI_Master; with NRF_SVD.SPI; with nRF.Timers; use nRF.Timers; with NRF_SVD.TIMER; with nRF.UART; use nRF.UART; with NRF_SVD.UART; package nRF.Device is pragma Elaborate_Body; P00 : aliased GPIO_Point := (Pin => 00); P01 : aliased GPIO_Point := (Pin => 01); P02 : aliased GPIO_Point := (Pin => 02); P03 : aliased GPIO_Point := (Pin => 03); P04 : aliased GPIO_Point := (Pin => 04); P05 : aliased GPIO_Point := (Pin => 05); P06 : aliased GPIO_Point := (Pin => 06); P07 : aliased GPIO_Point := (Pin => 07); P08 : aliased GPIO_Point := (Pin => 08); P09 : aliased GPIO_Point := (Pin => 09); P10 : aliased GPIO_Point := (Pin => 10); P11 : aliased GPIO_Point := (Pin => 11); P12 : aliased GPIO_Point := (Pin => 12); P13 : aliased GPIO_Point := (Pin => 13); P14 : aliased GPIO_Point := (Pin => 14); P15 : aliased GPIO_Point := (Pin => 15); P16 : aliased GPIO_Point := (Pin => 16); P17 : aliased GPIO_Point := (Pin => 17); P18 : aliased GPIO_Point := (Pin => 18); P19 : aliased GPIO_Point := (Pin => 19); P20 : aliased GPIO_Point := (Pin => 20); P21 : aliased GPIO_Point := (Pin => 21); P22 : aliased GPIO_Point := (Pin => 22); P23 : aliased GPIO_Point := (Pin => 23); P24 : aliased GPIO_Point := (Pin => 24); P25 : aliased GPIO_Point := (Pin => 25); P26 : aliased GPIO_Point := (Pin => 26); P27 : aliased GPIO_Point := (Pin => 27); P28 : aliased GPIO_Point := (Pin => 28); P29 : aliased GPIO_Point := (Pin => 29); P30 : aliased GPIO_Point := (Pin => 30); P31 : aliased GPIO_Point := (Pin => 31); RTC_0 : aliased Real_Time_Counter (NRF_SVD.RTC.RTC0_Periph'Access); RTC_1 : aliased Real_Time_Counter (NRF_SVD.RTC.RTC1_Periph'Access); -- Be carefull of shared resources between the TWI and SPI controllers. -- TWI_O and SPI_Master_0 cannot be used at the same time. -- TWI_1 and SPI_Master_1 cannot be used at the same time. -- -- See nRF Series Reference Manual, chapter Memory.Instantiation. TWI_0 : aliased TWI_Master (NRF_SVD.TWI.TWI0_Periph'Access); TWI_1 : aliased TWI_Master (NRF_SVD.TWI.TWI1_Periph'Access); SPI_Master_0 : aliased nRF.SPI_Master.SPI_Master (NRF_SVD.SPI.SPI0_Periph'Access); SPI_Master_1 : aliased nRF.SPI_Master.SPI_Master (NRF_SVD.SPI.SPI1_Periph'Access); Timer_0 : aliased Timer (NRF_SVD.TIMER.TIMER0_Periph'Access); Timer_1 : aliased Timer (NRF_SVD.TIMER.TIMER1_Periph'Access); Timer_2 : aliased Timer (NRF_SVD.TIMER.TIMER2_Periph'Access); Timer_3 : aliased Timer (NRF_SVD.TIMER.TIMER3_Periph'Access); Timer_4 : aliased Timer (NRF_SVD.TIMER.TIMER4_Periph'Access); UART_0 : aliased UART_Device (NRF_SVD.UART.UART0_Periph'Access); end nRF.Device;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016-2020, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with nRF.GPIO; use nRF.GPIO; with nRF.RTC; use nRF.RTC; with NRF_SVD.RTC; with nRF.TWI; use nRF.TWI; with NRF_SVD.TWI; with nRF.SPI_Master; use nRF.SPI_Master; with NRF_SVD.SPI; with nRF.Timers; use nRF.Timers; with NRF_SVD.TIMER; with nRF.UART; use nRF.UART; with NRF_SVD.UART; package nRF.Device is pragma Elaborate_Body; P00 : aliased GPIO_Point := (Pin => 00); P01 : aliased GPIO_Point := (Pin => 01); P02 : aliased GPIO_Point := (Pin => 02); P03 : aliased GPIO_Point := (Pin => 03); P04 : aliased GPIO_Point := (Pin => 04); P05 : aliased GPIO_Point := (Pin => 05); P06 : aliased GPIO_Point := (Pin => 06); P07 : aliased GPIO_Point := (Pin => 07); P08 : aliased GPIO_Point := (Pin => 08); P09 : aliased GPIO_Point := (Pin => 09); P10 : aliased GPIO_Point := (Pin => 10); P11 : aliased GPIO_Point := (Pin => 11); P12 : aliased GPIO_Point := (Pin => 12); P13 : aliased GPIO_Point := (Pin => 13); P14 : aliased GPIO_Point := (Pin => 14); P15 : aliased GPIO_Point := (Pin => 15); P16 : aliased GPIO_Point := (Pin => 16); P17 : aliased GPIO_Point := (Pin => 17); P18 : aliased GPIO_Point := (Pin => 18); P19 : aliased GPIO_Point := (Pin => 19); P20 : aliased GPIO_Point := (Pin => 20); P21 : aliased GPIO_Point := (Pin => 21); P22 : aliased GPIO_Point := (Pin => 22); P23 : aliased GPIO_Point := (Pin => 23); P24 : aliased GPIO_Point := (Pin => 24); P25 : aliased GPIO_Point := (Pin => 25); P26 : aliased GPIO_Point := (Pin => 26); P27 : aliased GPIO_Point := (Pin => 27); P28 : aliased GPIO_Point := (Pin => 28); P29 : aliased GPIO_Point := (Pin => 29); P30 : aliased GPIO_Point := (Pin => 30); P31 : aliased GPIO_Point := (Pin => 31); RTC_0 : aliased Real_Time_Counter (NRF_SVD.RTC.RTC0_Periph'Access); RTC_1 : aliased Real_Time_Counter (NRF_SVD.RTC.RTC1_Periph'Access); RTC_2 : aliased Real_Time_Counter (NRF_SVD.RTC.RTC2_Periph'Access); -- Be carefull of shared resources between the TWI and SPI controllers. -- TWI_O and SPI_Master_0 cannot be used at the same time. -- TWI_1 and SPI_Master_1 cannot be used at the same time. -- -- See nRF Series Reference Manual, chapter Memory.Instantiation. TWI_0 : aliased TWI_Master (NRF_SVD.TWI.TWI0_Periph'Access); TWI_1 : aliased TWI_Master (NRF_SVD.TWI.TWI1_Periph'Access); SPI_Master_0 : aliased nRF.SPI_Master.SPI_Master (NRF_SVD.SPI.SPI0_Periph'Access); SPI_Master_1 : aliased nRF.SPI_Master.SPI_Master (NRF_SVD.SPI.SPI1_Periph'Access); SPI_Master_2 : aliased nRF.SPI_Master.SPI_Master (NRF_SVD.SPI.SPI2_Periph'Access); Timer_0 : aliased Timer (NRF_SVD.TIMER.TIMER0_Periph'Access); Timer_1 : aliased Timer (NRF_SVD.TIMER.TIMER1_Periph'Access); Timer_2 : aliased Timer (NRF_SVD.TIMER.TIMER2_Periph'Access); Timer_3 : aliased Timer (NRF_SVD.TIMER.TIMER3_Periph'Access); Timer_4 : aliased Timer (NRF_SVD.TIMER.TIMER4_Periph'Access); UART_0 : aliased UART_Device (NRF_SVD.UART.UART0_Periph'Access); end nRF.Device;
Add missing devices
nRF.Device: Add missing devices
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
6b3020a4f3135ceb93fbf248b82535e48a4f6b51
src/asf-components-core-factory.adb
src/asf-components-core-factory.adb
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- Copyright (C) 2009, 2010, 2011, 2012, 2014, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Base; with ASF.Views.Nodes; with ASF.Views.Nodes.Jsf; with ASF.Components.Html.Selects; with ASF.Components.Core.Views; package body ASF.Components.Core.Factory is function Create_View return Base.UIComponent_Access; function Create_ViewAction return Base.UIComponent_Access; function Create_ViewMetaData return Base.UIComponent_Access; function Create_ViewParameter return Base.UIComponent_Access; function Create_Parameter return Base.UIComponent_Access; function Create_SelectItem return Base.UIComponent_Access; function Create_SelectItems return Base.UIComponent_Access; -- ------------------------------ -- Create an UIView component -- ------------------------------ function Create_View return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIView; end Create_View; -- ------------------------------ -- Create an UIViewAction component -- ------------------------------ function Create_ViewAction return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewAction; end Create_ViewAction; -- ------------------------------ -- Create an UIViewMetaData component -- ------------------------------ function Create_ViewMetaData return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewMetaData; end Create_ViewMetaData; -- ------------------------------ -- Create an UIViewParameter component -- ------------------------------ function Create_ViewParameter return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewParameter; end Create_ViewParameter; -- ------------------------------ -- Create an UIParameter component -- ------------------------------ function Create_Parameter return Base.UIComponent_Access is begin return new ASF.Components.Core.UIParameter; end Create_Parameter; -- ------------------------------ -- Create an UISelectItem component -- ------------------------------ function Create_SelectItem return Base.UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectItem; end Create_SelectItem; -- ------------------------------ -- Create an UISelectItems component -- ------------------------------ function Create_SelectItems return Base.UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectItems; end Create_SelectItems; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/core"; ATTRIBUTE_TAG : aliased constant String := "attribute"; CONVERT_DATE_TIME_TAG : aliased constant String := "convertDateTime"; CONVERTER_TAG : aliased constant String := "converter"; FACET_TAG : aliased constant String := "facet"; METADATA_TAG : aliased constant String := "metadata"; PARAM_TAG : aliased constant String := "param"; SELECT_ITEM_TAG : aliased constant String := "selectItem"; SELECT_ITEMS_TAG : aliased constant String := "selectItems"; VALIDATE_LENGTH_TAG : aliased constant String := "validateLength"; VALIDATE_LONG_RANGE_TAG : aliased constant String := "validateLongRange"; VALIDATOR_TAG : aliased constant String := "validator"; VIEW_TAG : aliased constant String := "view"; VIEW_ACTION_TAG : aliased constant String := "viewAction"; VIEW_PARAM_TAG : aliased constant String := "viewParam"; -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ procedure Register (Factory : in out ASF.Factory.Component_Factory) is begin ASF.Factory.Register (Factory, URI => URI'Access, Name => ATTRIBUTE_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Attribute_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => CONVERT_DATE_TIME_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Convert_Date_Time_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => CONVERTER_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Converter_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => FACET_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Facet_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => METADATA_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Metadata_Tag_Node'Access, Create => Create_ViewMetaData'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => PARAM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Parameter'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ITEM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectItem'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ITEMS_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectItems'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATE_LENGTH_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Length_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATE_LONG_RANGE_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Range_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATOR_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_View'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_ACTION_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_ViewAction'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_PARAM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_ViewParameter'Access); end Register; end ASF.Components.Core.Factory;
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- Copyright (C) 2009, 2010, 2011, 2012, 2014, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Base; with ASF.Views.Nodes; with ASF.Views.Nodes.Jsf; with ASF.Components.Html.Selects; with ASF.Components.Core.Views; package body ASF.Components.Core.Factory is function Create_View return Base.UIComponent_Access; function Create_ViewAction return Base.UIComponent_Access; function Create_ViewMetaData return Base.UIComponent_Access; function Create_ViewParameter return Base.UIComponent_Access; function Create_Parameter return Base.UIComponent_Access; function Create_SelectItem return Base.UIComponent_Access; function Create_SelectItems return Base.UIComponent_Access; -- ------------------------------ -- Create an UIView component -- ------------------------------ function Create_View return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIView; end Create_View; -- ------------------------------ -- Create an UIViewAction component -- ------------------------------ function Create_ViewAction return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewAction; end Create_ViewAction; -- ------------------------------ -- Create an UIViewMetaData component -- ------------------------------ function Create_ViewMetaData return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewMetaData; end Create_ViewMetaData; -- ------------------------------ -- Create an UIViewParameter component -- ------------------------------ function Create_ViewParameter return Base.UIComponent_Access is begin return new ASF.Components.Core.Views.UIViewParameter; end Create_ViewParameter; -- ------------------------------ -- Create an UIParameter component -- ------------------------------ function Create_Parameter return Base.UIComponent_Access is begin return new ASF.Components.Core.UIParameter; end Create_Parameter; -- ------------------------------ -- Create an UISelectItem component -- ------------------------------ function Create_SelectItem return Base.UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectItem; end Create_SelectItem; -- ------------------------------ -- Create an UISelectItems component -- ------------------------------ function Create_SelectItems return Base.UIComponent_Access is begin return new ASF.Components.Html.Selects.UISelectItems; end Create_SelectItems; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/core"; ATTRIBUTE_TAG : aliased constant String := "attribute"; CONVERT_DATE_TIME_TAG : aliased constant String := "convertDateTime"; CONVERTER_TAG : aliased constant String := "converter"; FACET_TAG : aliased constant String := "facet"; METADATA_TAG : aliased constant String := "metadata"; PARAM_TAG : aliased constant String := "param"; SELECT_ITEM_TAG : aliased constant String := "selectItem"; SELECT_ITEMS_TAG : aliased constant String := "selectItems"; VALIDATE_LENGTH_TAG : aliased constant String := "validateLength"; VALIDATE_LONG_RANGE_TAG : aliased constant String := "validateLongRange"; VALIDATE_REGEX_TAG : aliased constant String := "validateRegex"; VALIDATOR_TAG : aliased constant String := "validator"; VIEW_TAG : aliased constant String := "view"; VIEW_ACTION_TAG : aliased constant String := "viewAction"; VIEW_PARAM_TAG : aliased constant String := "viewParam"; -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ procedure Register (Factory : in out ASF.Factory.Component_Factory) is begin ASF.Factory.Register (Factory, URI => URI'Access, Name => ATTRIBUTE_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Attribute_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => CONVERT_DATE_TIME_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Convert_Date_Time_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => CONVERTER_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Converter_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => FACET_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Facet_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => METADATA_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Metadata_Tag_Node'Access, Create => Create_ViewMetaData'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => PARAM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_Parameter'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ITEM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectItem'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => SELECT_ITEMS_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_SelectItems'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATE_LENGTH_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Length_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATE_LONG_RANGE_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Range_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATE_REGEX_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Regex_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VALIDATOR_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_TAG'Access, Tag => ASF.Views.Nodes.Jsf.Create_Validator_Tag_Node'Access, Create => null); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_View'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_ACTION_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_ViewAction'Access); ASF.Factory.Register (Factory, URI => URI'Access, Name => VIEW_PARAM_TAG'Access, Tag => Create_Component_Node'Access, Create => Create_ViewParameter'Access); end Register; end ASF.Components.Core.Factory;
Define and register the <f:validateRegex> tag
Define and register the <f:validateRegex> tag
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
989dd0c632fe64f101be419d3ae844f20da41ea6
src/ado-sequences.ads
src/ado-sequences.ads
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- 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.Finalization; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with ADO.Sessions; with ADO.Objects; limited with ADO.Sessions.Factory; -- The sequence generator is responsible for creating unique ID's -- across all database objects. -- -- Each table can be associated with a sequence generator. -- The sequence factory is shared by several sessions and the -- implementation is thread-safe. -- -- The HiLoGenerator implements a simple High Low sequence generator -- by using sequences that avoid to access the database. -- -- Example: -- -- F : Factory; -- Id : Identifier; -- -- Allocate (Manager => F, Name => "user", Id => Id); -- package ADO.Sequences is type Session_Factory_Access is access all ADO.Sessions.Factory.Session_Factory'Class; -- ------------------------------ -- Abstract sequence generator -- ------------------------------ type Generator is abstract new Ada.Finalization.Limited_Controlled with private; type Generator_Access is access all Generator'Class; -- Get the name of the sequence. function Get_Sequence_Name (Gen : in Generator'Class) return String; -- Allocate an identifier using the generator. procedure Allocate (Gen : in out Generator; Id : in out Objects.Object_Record'Class) is abstract; -- Get a session to connect to the database. function Get_Session (Gen : in Generator) return ADO.Sessions.Master_Session'Class; type Generator_Factory is access function (Sess_Factory : in Session_Factory_Access) return Generator_Access; -- ------------------------------ -- Sequence factory -- ------------------------------ -- The sequence <b>Factory</b> allocates unique ids for new objects. -- The factory is shared by all connections to the same database. type Factory is limited private; type Factory_Access is access all Factory; -- Allocate a unique identifier for the given sequence. procedure Allocate (Manager : in out Factory; Id : in out Objects.Object_Record'Class); -- Set a generator to be used for the given sequence. procedure Set_Generator (Manager : in out Factory; Name : in String; Gen : in Generator_Access); -- Set the default factory for creating generators. -- The default factory is the HiLo generator. procedure Set_Default_Generator (Manager : in out Factory; Factory : in Generator_Factory; Sess_Factory : in Session_Factory_Access); private use Ada.Strings.Unbounded; type Generator is abstract new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; Factory : Session_Factory_Access; end record; -- Each sequence generator is accessed through a protected type -- to make sure the allocation is unique and works in multi-threaded -- environments. protected type Sequence_Generator is -- Allocate a unique identifier for the given sequence. procedure Allocate (Id : in out Objects.Object_Record'Class); procedure Set_Generator (Name : in Unbounded_String; Gen : in Generator_Access); -- Free the generator procedure Clear; private Generator : Generator_Access; end Sequence_Generator; type Sequence_Generator_Access is access all Sequence_Generator; -- Map to keep track of allocation generators for each sequence. package Sequence_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Sequence_Generator_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => "="); -- The sequence factory map is also accessed through a protected type. protected type Factory_Map is -- Get the sequence generator associated with the name. -- If there is no such generator, an entry is created by using -- the default generator. procedure Get_Generator (Name : in Unbounded_String; Gen : out Sequence_Generator_Access); -- Set the sequence generator associated with the name. procedure Set_Generator (Name : in Unbounded_String; Gen : in Sequence_Generator_Access); -- Set the default sequence generator. procedure Set_Default_Generator (Gen : in Generator_Factory; Factory : in Session_Factory_Access); -- Clear the factory map. procedure Clear; private Map : Sequence_Maps.Map; Create_Generator : Generator_Factory; Sess_Factory : Session_Factory_Access; end Factory_Map; type Factory is new Ada.Finalization.Limited_Controlled with record Map : Factory_Map; end record; overriding procedure Finalize (Manager : in out Factory); end ADO.Sequences;
----------------------------------------------------------------------- -- ADO Sequences -- 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. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with ADO.Sessions; with ADO.Objects; limited with ADO.Sessions.Factory; -- == Sequence Generators == -- The sequence generator is responsible for creating unique ID's -- across all database objects. -- -- Each table can be associated with a sequence generator. -- The sequence factory is shared by several sessions and the -- implementation is thread-safe. -- -- The HiLoGenerator implements a simple High Low sequence generator -- by using sequences that avoid to access the database. -- -- Example: -- -- F : Factory; -- Id : Identifier; -- -- Allocate (Manager => F, Name => "user", Id => Id); -- -- @include ado-sequences-hilo.ads package ADO.Sequences is type Session_Factory_Access is access all ADO.Sessions.Factory.Session_Factory'Class; -- ------------------------------ -- Abstract sequence generator -- ------------------------------ type Generator is abstract new Ada.Finalization.Limited_Controlled with private; type Generator_Access is access all Generator'Class; -- Get the name of the sequence. function Get_Sequence_Name (Gen : in Generator'Class) return String; -- Allocate an identifier using the generator. procedure Allocate (Gen : in out Generator; Id : in out Objects.Object_Record'Class) is abstract; -- Get a session to connect to the database. function Get_Session (Gen : in Generator) return ADO.Sessions.Master_Session'Class; type Generator_Factory is access function (Sess_Factory : in Session_Factory_Access) return Generator_Access; -- ------------------------------ -- Sequence factory -- ------------------------------ -- The sequence <b>Factory</b> allocates unique ids for new objects. -- The factory is shared by all connections to the same database. type Factory is limited private; type Factory_Access is access all Factory; -- Allocate a unique identifier for the given sequence. procedure Allocate (Manager : in out Factory; Id : in out Objects.Object_Record'Class); -- Set a generator to be used for the given sequence. procedure Set_Generator (Manager : in out Factory; Name : in String; Gen : in Generator_Access); -- Set the default factory for creating generators. -- The default factory is the HiLo generator. procedure Set_Default_Generator (Manager : in out Factory; Factory : in Generator_Factory; Sess_Factory : in Session_Factory_Access); private use Ada.Strings.Unbounded; type Generator is abstract new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; Factory : Session_Factory_Access; end record; -- Each sequence generator is accessed through a protected type -- to make sure the allocation is unique and works in multi-threaded -- environments. protected type Sequence_Generator is -- Allocate a unique identifier for the given sequence. procedure Allocate (Id : in out Objects.Object_Record'Class); procedure Set_Generator (Name : in Unbounded_String; Gen : in Generator_Access); -- Free the generator procedure Clear; private Generator : Generator_Access; end Sequence_Generator; type Sequence_Generator_Access is access all Sequence_Generator; -- Map to keep track of allocation generators for each sequence. package Sequence_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Sequence_Generator_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => "="); -- The sequence factory map is also accessed through a protected type. protected type Factory_Map is -- Get the sequence generator associated with the name. -- If there is no such generator, an entry is created by using -- the default generator. procedure Get_Generator (Name : in Unbounded_String; Gen : out Sequence_Generator_Access); -- Set the sequence generator associated with the name. procedure Set_Generator (Name : in Unbounded_String; Gen : in Sequence_Generator_Access); -- Set the default sequence generator. procedure Set_Default_Generator (Gen : in Generator_Factory; Factory : in Session_Factory_Access); -- Clear the factory map. procedure Clear; private Map : Sequence_Maps.Map; Create_Generator : Generator_Factory; Sess_Factory : Session_Factory_Access; end Factory_Map; type Factory is new Ada.Finalization.Limited_Controlled with record Map : Factory_Map; end record; overriding procedure Finalize (Manager : in out Factory); end ADO.Sequences;
Add some documentation on sequences
Add some documentation on sequences
Ada
apache-2.0
stcarrez/ada-ado
e7866cb48f06fa95ba0e3f1a0b609e954282b13d
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 Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); 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 Log.Error ("Not enough data to get a uint8"); 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 Log.Error ("Not enough data to get a uint16"); 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 Log.Error ("Not enough data to get a uint32"); 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 => Log.Error ("Invalid attribute type {0}", MAT.EVents.Attribute_Type'Image (Kind)); 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; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; 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 Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); 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 Log.Error ("Not enough data to get a uint8"); 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 Log.Error ("Not enough data to get a uint16"); 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 Log.Error ("Not enough data to get a uint32"); 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 => Log.Error ("Invalid attribute type {0}", MAT.EVents.Attribute_Type'Image (Kind)); 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; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; end MAT.Readers.Marshaller;
Fix instantiation issue
Fix instantiation issue
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
512d187ccb10d292b27f8c3281ff5cb6f7206ec1
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; 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; end MAT.Readers.Marshaller;
Implement the Get_Target_Type generic function
Implement the Get_Target_Type generic function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
cfed6ccb1ebf228c052929685ee29d06818868b0
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; 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;
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 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 Ada.Text_IO; with Ada.Calendar; with Ada.Containers; with Ada.Finalization; with Util.Streams.Texts; -- = Performance Measurements = -- -- Performance measurements is often made using profiling tools such as GNU gprof or others. -- This profiling is however not always appropriate for production or release delivery. -- The mechanism presented here is a lightweight performance measurement that can be -- used in production systems. -- -- The Ada package `Util.Measures` defines the types and operations to make -- performance measurements. It is designed to be used for production and multi-threaded -- environments. -- -- == Create the measure set == -- -- Measures are collected in a `Measure_Set`. Each measure has a name, a counter and -- a sum of time spent for all the measure. The measure set should be declared as some -- global variable. The implementation is thread safe meaning that a measure set can -- be used by several threads at the same time. It can also be associated with -- a per-thread data (or task attribute). -- -- To declare the measure set, use: -- -- with Util.Measures; -- ... -- Perf : Util.Measures.Measure_Set; -- -- == Measure the implementation == -- -- A measure is made by creating a variable of type `Stamp`. The declaration of -- this variable marks the begining of the measure. The measure ends at the -- next call to the `Report` procedure. -- -- with Util.Measures; -- ... -- declare -- Start : Util.Measures.Stamp; -- begin -- ... -- Util.Measures.Report (Perf, Start, "Measure for a block"); -- end; -- -- When the `Report` procedure is called, the time that elapsed between the creation of -- the `Start` variable and the procedure call is computed. This time is -- then associated with the measure title and the associated counter is incremented. -- The precision of the measured time depends on the system. On GNU/Linux, it uses -- `gettimeofday`. -- -- If the block code is executed several times, the measure set will report -- the number of times it was executed. -- -- == Reporting results == -- -- After measures are collected, the results can be saved in a file or in -- an output stream. When saving the measures, the measure set is cleared. -- -- Util.Measures.Write (Perf, "Title of measures", -- Ada.Text_IO.Standard_Output); -- -- == Measure Overhead == -- -- The overhead introduced by the measurement is quite small as it does not exceeds 1.5 us -- on a 2.6 Ghz Core Quad. -- -- == What must be measured == -- -- Defining a lot of measurements for a production system is in general not very useful. -- Measurements should be relatively high level measurements. For example: -- -- * Loading or saving a file -- * Rendering a page in a web application -- * Executing a database query -- 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;
Integrate documentation about measures
Integrate documentation about measures
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c62e507abe6e04afb9433426b39939bfb5dc183a
src/os-linux/util-streams-raw.ads
src/os-linux/util-streams-raw.ads
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Unix based systems -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Systems.Os; -- The <b>Util.Streams.Raw</b> package provides a stream directly on top of -- file system operations <b>read</b> and <b>write</b>. package Util.Streams.Raw is -- ----------------------- -- File stream -- ----------------------- -- The <b>Raw_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with private; type Raw_Stream_Access is access all Raw_Stream'Class; -- Initialize the raw stream to read and write on the given file descriptor. procedure Initialize (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type); -- Close the stream. overriding procedure Close (Stream : in out Raw_Stream); -- Write the buffer array to the output stream. procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; -- Flush the stream and release the buffer. procedure Finalize (Object : in out Raw_Stream); type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Util.Systems.Os.File_Type := Util.Systems.Os.NO_FILE; end record; end Util.Streams.Raw;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Unix based systems -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Systems.Os; with Util.Systems.Types; -- The <b>Util.Streams.Raw</b> package provides a stream directly on top of -- file system operations <b>read</b> and <b>write</b>. package Util.Streams.Raw is -- ----------------------- -- File stream -- ----------------------- -- The <b>Raw_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with private; type Raw_Stream_Access is access all Raw_Stream'Class; -- Initialize the raw stream to read and write on the given file descriptor. procedure Initialize (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type); -- Close the stream. overriding procedure Close (Stream : in out Raw_Stream); -- Write the buffer array to the output stream. procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Reposition the read/write file offset. procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode); private use Ada.Streams; -- Flush the stream and release the buffer. procedure Finalize (Object : in out Raw_Stream); type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Util.Systems.Os.File_Type := Util.Systems.Os.NO_FILE; end record; end Util.Streams.Raw;
Declare the Seek procedure to set the file read/write position
Declare the Seek procedure to set the file read/write position
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0d5701ddf12b3f55080bc8d65dfd8c56ce37a9b3
src/el-utils.adb
src/el-utils.adb
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name : in String; Item : in Util.Beans.Objects.Object); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then declare Value : constant String := Into.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name : in String; Item : in Util.Properties.Value) is Value : constant String := Util.Properties.To_String (Item); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then Log.Debug ("Adding config {0} = {1}", Name, Value); Into.Set_Value (Name, Item); else declare New_Value : constant Object := Expand (Value, Local_Context); begin Log.Debug ("Adding config {0} = {1}", Name, Util.Beans.Objects.To_String (New_Value)); if Util.Beans.Objects.Is_Null (New_Value) then Into.Set (Name, ""); else Into.Set_Value (Name, New_Value); end if; end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012, 2017, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("EL.Utils"); procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class; Copy : in Boolean); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class; Copy : in Boolean) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name : in String; Item : in Util.Beans.Objects.Object); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then declare Value : constant String := Into.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name : in String; Item : in Util.Properties.Value) is Value : constant String := Util.Properties.To_String (Item); begin if Util.Strings.Index (Value, '{') > 0 or else Util.Strings.Index (Value, '}') > 0 then declare New_Value : constant Object := Expand (Value, Local_Context); begin Log.Debug ("Adding config {0} = {1}", Name, Util.Beans.Objects.To_String (New_Value)); if Util.Beans.Objects.Is_Null (New_Value) then Into.Set (Name, ""); else Into.Set_Value (Name, New_Value); end if; end; elsif Copy then Log.Debug ("Adding config {0} = {1}", Name, Value); Into.Set_Value (Name, Item); end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; procedure Expand (Config : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is begin Expand (Config, Config, Context, False); end Expand; procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is begin Expand (Source, Into, Context, True); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
Implement Expand to replace properties in place and avoid unecessary copies
Implement Expand to replace properties in place and avoid unecessary copies
Ada
apache-2.0
stcarrez/ada-el
ed83c497f707450ffd8613d6e49324d6c4734da6
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Get the driver index that corresponds to the driver for this database connection string. -- ------------------------------ function Get_Driver (Config : in Configuration) return Driver_Index is Driver : constant Driver_Access := Get_Driver (Config.Get_Driver); begin if Driver = null then return Driver_Index'First; else return Driver.Get_Driver_Index; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Driver : Driver_Access; Log_URI : constant String := Config.Get_Log_URI; begin Driver := Get_Driver (Config.Get_Driver); if Driver = null then Log.Error ("No driver found for connection {0}", Log_URI); raise ADO.Configs.Connection_Error with "Data source is not initialized: driver '" & Config.Get_Driver & "' not found"; end if; Driver.Create_Connection (Config, Result); if Result.Is_Null then Log.Error ("Driver {0} failed to create connection {0}", Driver.Name.all, Log_URI); raise ADO.Configs.Connection_Error with "Data source is not initialized: driver error"; end if; Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Log_URI); raise; end Create_Connection; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database_Connection'Class (Database).Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Debug ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Log.Info ("Initialising driver {0}", Lib); Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Debug ("Get driver {0}", Name); if Name'Length = 0 then return null; end if; for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Get the driver index that corresponds to the driver for this database connection string. -- ------------------------------ function Get_Driver (Config : in Configuration) return Driver_Index is Driver : constant Driver_Access := Get_Driver (Config.Get_Driver); begin if Driver = null then return Driver_Index'First; else return Driver.Get_Driver_Index; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Driver : Driver_Access; Log_URI : constant String := Config.Get_Log_URI; begin Driver := Get_Driver (Config.Get_Driver); if Driver = null then Log.Error ("No driver found for connection {0}", Log_URI); raise ADO.Configs.Connection_Error with "Data source is not initialized: driver '" & Config.Get_Driver & "' not found"; end if; Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Log_URI); raise; end Create_Connection; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database_Connection'Class (Database).Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Debug ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Log.Info ("Initialising driver {0}", Lib); Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Debug ("Get driver {0}", Name); if Name'Length = 0 then return null; end if; for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Remove check of database driver connection because the post condition now guarantees it is never null
Remove check of database driver connection because the post condition now guarantees it is never null
Ada
apache-2.0
stcarrez/ada-ado
0f8a3c4f50bec86224687da09c85fb721e4664b9
src/ado-drivers-connections.adb
src/ado-drivers-connections.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 Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Util.Log; use Ada.Strings.Fixed; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers.Connections"); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; type Driver_Initialize_Access is not null access procedure; procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 > Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Integer is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Fix some compilation warnings
Fix some compilation warnings
Ada
apache-2.0
Letractively/ada-ado
2cccc37423686093113eb51a01a4b57102bb5aad
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; Memory.Frames := Frames.Create_Root; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.Memory_Slots.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; end Memory_Allocator; end MAT.Memory.Targets;
Implement the Probe_Malloc operation
Implement the Probe_Malloc operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat