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
d72873ddc31dcaf3c198a03bbe80d8a10c16ab28
regtests/wiki-tests.ads
regtests/wiki-tests.ads
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package Wiki.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test_Case with record Writer : Integer; Name : Ada.Strings.Unbounded.Unbounded_String; File : Ada.Strings.Unbounded.Unbounded_String; Expect : Ada.Strings.Unbounded.Unbounded_String; Result : Ada.Strings.Unbounded.Unbounded_String; Source : Wiki.Wiki_Syntax; Format : Wiki.Wiki_Syntax; Is_Html : Boolean := False; end record; type Test_Case_Access is access all Test; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String; -- Perform the test. overriding procedure Run_Test (T : in out Test); -- Test rendering a wiki text in HTML or text. procedure Test_Render (T : in out Test); end Wiki.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package Wiki.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test_Case with record Writer : Integer; Name : Ada.Strings.Unbounded.Unbounded_String; File : Ada.Strings.Unbounded.Unbounded_String; Expect : Ada.Strings.Unbounded.Unbounded_String; Result : Ada.Strings.Unbounded.Unbounded_String; Source : Wiki.Wiki_Syntax; Format : Wiki.Wiki_Syntax; Is_Html : Boolean := False; Is_Cvt : Boolean := False; end record; type Test_Case_Access is access all Test; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String; -- Perform the test. overriding procedure Run_Test (T : in out Test); -- Test rendering a wiki text in HTML or text. procedure Test_Render (T : in out Test); end Wiki.Tests;
Add Is_Cvt to text Wiki to Wiki convertion
Add Is_Cvt to text Wiki to Wiki convertion
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5d0e2524c3c75990867f013e55b9eeb667452113
src/base/beans/util-beans.ads
src/base/beans/util-beans.ads
----------------------------------------------------------------------- -- util-beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010, 2018, 2019, 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. ----------------------------------------------------------------------- -- = Ada Beans = -- A [Java Bean](http://en.wikipedia.org/wiki/JavaBean) is an object that -- allows to access its properties through getters and setters. Java Beans -- rely on the use of Java introspection to discover the Java Bean object properties. -- -- An Ada Bean has some similarities with the Java Bean as it tries to expose -- an object through a set of common interfaces. Since Ada does not have introspection, -- some developer work is necessary. The Ada Bean framework consists of: -- -- * An `Object` concrete type that allows to hold any data type such -- as boolean, integer, floats, strings, dates and Ada bean objects. -- * A `Bean` interface that exposes a `Get_Value` and `Set_Value` -- operation through which the object properties can be obtained and modified. -- * A `Method_Bean` interface that exposes a set of method bindings -- that gives access to the methods provided by the Ada Bean object. -- -- The benefit of Ada beans comes when you need to get a value or invoke -- a method on an object but you don't know at compile time the object or method. -- That step being done later through some external configuration or presentation file. -- -- The Ada Bean framework is the basis for the implementation of -- Ada Server Faces and Ada EL. It allows the presentation layer to -- access information provided by Ada beans. -- -- To use the packages described here, use the following GNAT project: -- -- with "utilada_base"; -- -- @include util-beans-objects.ads -- @include util-beans-objects-maps.ads -- @include util-beans-objects-vectors.ads -- @include util-beans-objects-datasets.ads -- @include util-beans-basic.ads package Util.Beans is pragma Preelaborate; end Util.Beans;
----------------------------------------------------------------------- -- util-beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010, 2018, 2019, 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. ----------------------------------------------------------------------- -- = Ada Beans = -- A [Java Bean](http://en.wikipedia.org/wiki/JavaBean) is an object that -- allows to access its properties through getters and setters. Java Beans -- rely on the use of Java introspection to discover the Java Bean object properties. -- -- An Ada Bean has some similarities with the Java Bean as it tries to expose -- an object through a set of common interfaces. Since Ada does not have introspection, -- some developer work is necessary. The Ada Bean framework consists of: -- -- * An `Object` concrete type that allows to hold any data type such -- as boolean, integer, floats, strings, dates and Ada bean objects. -- * A `Bean` interface that exposes a `Get_Value` and `Set_Value` -- operation through which the object properties can be obtained and modified. -- * A `Method_Bean` interface that exposes a set of method bindings -- that gives access to the methods provided by the Ada Bean object. -- -- The benefit of Ada beans comes when you need to get a value or invoke -- a method on an object but you don't know at compile time the object or method. -- That step being done later through some external configuration or presentation file. -- -- The Ada Bean framework is the basis for the implementation of -- Ada Server Faces and Ada EL. It allows the presentation layer to -- access information provided by Ada beans. -- -- To use the packages described here, use the following GNAT project: -- -- with "utilada_base"; -- -- @include util-beans-objects.ads -- @include util-beans-objects-maps.ads -- @include util-beans-objects-vectors.ads -- @include util-beans-objects-datasets.ads -- @include util-beans-objects-iterators.ads -- @include util-beans-basic.ads package Util.Beans is pragma Preelaborate; end Util.Beans;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
39a8d9168a8aff624927b06276eb5d1b07b03505
awa/plugins/awa-settings/src/awa-settings.adb
awa/plugins/awa-settings/src/awa-settings.adb
----------------------------------------------------------------------- -- awa-settings -- Settings module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with AWA.Settings.Modules; package body AWA.Settings is -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in String) return String is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; Value : Ada.Strings.Unbounded.Unbounded_String; begin Mgr.Get (Name, Default, Value); return Ada.Strings.Unbounded.To_String (Value); end Get_User_Setting; -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in Integer) return Integer is begin return Default; end Get_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in String) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Value); end Set_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in Integer) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Util.Strings.Image (Value)); end Set_User_Setting; end AWA.Settings;
----------------------------------------------------------------------- -- awa-settings -- Settings module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with AWA.Settings.Modules; package body AWA.Settings is -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in String) return String is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; Value : Ada.Strings.Unbounded.Unbounded_String; begin Mgr.Get (Name, Default, Value); return Ada.Strings.Unbounded.To_String (Value); end Get_User_Setting; -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in Integer) return Integer is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; Value : Ada.Strings.Unbounded.Unbounded_String; begin Mgr.Get (Name, Integer'Image (Default), Value); return Integer'Value (Ada.Strings.Unbounded.To_String (Value)); end Get_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in String) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Value); end Set_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in Integer) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Util.Strings.Image (Value)); end Set_User_Setting; end AWA.Settings;
Implement Get_User_Setting for integer
Implement Get_User_Setting for integer
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5e7c0795589e86a1f00e193d9476aef24ded8ba4
src/util-concurrent-pools.adb
src/util-concurrent-pools.adb
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- Copyright (C) 2011, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Pools is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ procedure Get_Instance (From : in out Pool; Item : out Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then From.List.Get_Instance (Item); else select From.List.Get_Instance (Item); or delay Wait; raise Timeout; end select; end if; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Into : in out Pool; Item : in Element_Type) is begin Into.List.Release (Item); end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Into : in out Pool; Capacity : in Positive) is begin Into.List.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Release the pool elements. -- ------------------------------ overriding procedure Finalize (Object : in out Pool) is begin Object.List.Set_Size (0); end Finalize; -- Pool of objects protected body Protected_Pool is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ entry Get_Instance (Item : out Element_Type) when Available > 0 is begin Item := Elements (Available); Available := Available - 1; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Item : in Element_Type) is begin Available := Available + 1; Elements (Available) := Item; end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); begin if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (1 .. Capacity); else declare New_Array : constant Element_Array_Access := new Element_Array (1 .. Capacity); begin if Capacity > Elements'Size then New_Array (1 .. Elements'Last) := Elements (1 .. Elements'Last); else New_Array (1 .. Capacity) := Elements (1 .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; end Protected_Pool; end Util.Concurrent.Pools;
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- Copyright (C) 2011, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Pools is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ procedure Get_Instance (From : in out Pool; Item : out Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then From.List.Get_Instance (Item); else select From.List.Get_Instance (Item); or delay Wait; raise Timeout; end select; end if; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Into : in out Pool; Item : in Element_Type) is begin Into.List.Release (Item); end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Into : in out Pool; Capacity : in Positive) is begin Into.List.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Get the number of available elements in the pool. -- ------------------------------ procedure Get_Available (From : in out Pool; Available : out Natural) is begin Available := From.List.Get_Available; end Get_Available; -- ------------------------------ -- Release the pool elements. -- ------------------------------ overriding procedure Finalize (Object : in out Pool) is begin Object.List.Set_Size (0); end Finalize; -- Pool of objects protected body Protected_Pool is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ entry Get_Instance (Item : out Element_Type) when Available > 0 is begin Item := Elements (Available); Available := Available - 1; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Item : in Element_Type) is begin Available := Available + 1; Elements (Available) := Item; end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); begin if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (1 .. Capacity); else declare New_Array : constant Element_Array_Access := new Element_Array (1 .. Capacity); begin if Capacity > Elements'Size then New_Array (1 .. Elements'Last) := Elements (1 .. Elements'Last); else New_Array (1 .. Capacity) := Elements (1 .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; -- ------------------------------ -- Get the number of available elements. -- ------------------------------ function Get_Available return Natural is begin return Available; end Get_Available; end Protected_Pool; end Util.Concurrent.Pools;
Implement the Get_Available procedure and protected function
Implement the Get_Available procedure and protected function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0ada5c17372df3eb3859d7d4d981217f7bcadae6
src/util-commands-drivers.ads
src/util-commands-drivers.ads
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; private with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Ordered_Maps; -- == Command line driver == -- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line -- tools that have different commands identified by a name. generic -- The command execution context. type Context_Type (<>) is limited private; Driver_Name : String := "Drivers"; package Util.Commands.Drivers is -- A simple command handler executed when the command with the given name is executed. type Command_Handler is not null access procedure (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- A more complex command handler that has a command instance as context. type Command_Type is abstract tagged limited private; type Command_Access is access all Command_Type'Class; -- Execute the command with the arguments. The command name is passed with the command -- arguments. procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Write the help associated with the command. procedure Help (Command : in Command_Type; Context : in out Context_Type) is abstract; -- Write the command usage. procedure Usage (Command : in Command_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); type Help_Command_Type is new Command_Type with private; -- Execute the help command with the arguments. -- Print the help for every registered command. overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. procedure Help (Command : in Help_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited private; -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : in String); -- Set the driver usage printed in the usage. procedure Set_Usage (Driver : in out Driver_Type; Usage : in String); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler); -- Find the command having the given name. -- Returns null if the command was not found. function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access; -- Execute the command registered under the given name. procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); private package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Command_Access, "<" => "<"); type Command_Type is abstract tagged limited record Driver : access Driver_Type'Class; end record; type Help_Command_Type is new Command_Type with null record; type Handler_Command_Type is new Command_Type with record Handler : Command_Handler; end record; -- Execute the command with the arguments. overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited record List : Command_Maps.Map; Desc : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; private with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Ordered_Maps; -- == Command line driver == -- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line -- tools that have different commands identified by a name. generic -- The command execution context. type Context_Type (<>) is limited private; Driver_Name : String := "Drivers"; package Util.Commands.Drivers is -- A simple command handler executed when the command with the given name is executed. type Command_Handler is not null access procedure (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- A more complex command handler that has a command instance as context. type Command_Type is abstract tagged limited private; type Command_Access is access all Command_Type'Class; -- Execute the command with the arguments. The command name is passed with the command -- arguments. procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Write the help associated with the command. procedure Help (Command : in Command_Type; Context : in out Context_Type) is abstract; -- Write the command usage. procedure Usage (Command : in Command_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); type Help_Command_Type is new Command_Type with private; -- Execute the help command with the arguments. -- Print the help for every registered command. overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. procedure Help (Command : in Help_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited private; -- Report the command usage. procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class); -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : in String); -- Set the driver usage printed in the usage. procedure Set_Usage (Driver : in out Driver_Type; Usage : in String); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler); -- Find the command having the given name. -- Returns null if the command was not found. function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access; -- Execute the command registered under the given name. procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); private package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Command_Access, "<" => "<"); type Command_Type is abstract tagged limited record Driver : access Driver_Type'Class; end record; type Help_Command_Type is new Command_Type with null record; type Handler_Command_Type is new Command_Type with record Handler : Command_Handler; end record; -- Execute the command with the arguments. overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited record List : Command_Maps.Map; Desc : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands.Drivers;
Declare the Usage procedure
Declare the Usage procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b61abee61fbf05724af236310813b865944c5a9c
regtests/asf-applications-tests.ads
regtests/asf-applications-tests.ads
----------------------------------------------------------------------- -- asf-applications-tests - ASF Application tests using ASFUnit -- 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.Tests; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Util.Beans.Basic.Lists; with Ada.Strings.Unbounded; package ASF.Applications.Tests is use Ada.Strings.Unbounded; Test_Exception : exception; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Initialize the test application overriding procedure Set_Up (T : in out Test); -- Test a GET request on a static file served by the File_Servlet. procedure Test_Get_File (T : in out Test); -- Test a GET 404 error on missing static file served by the File_Servlet. procedure Test_Get_404 (T : in out Test); -- Test a GET request on the measure servlet procedure Test_Get_Measures (T : in out Test); -- Test an invalid HTTP request. procedure Test_Invalid_Request (T : in out Test); -- Test a GET+POST request with submitted values and an action method called on the bean. procedure Test_Form_Post (T : in out Test); -- Test a POST request with an invalid submitted value procedure Test_Form_Post_Validation_Error (T : in out Test); -- Test a GET+POST request with form having <h:selectOneMenu> element. procedure Test_Form_Post_Select (T : in out Test); -- Test a POST request to invoke a bean method. procedure Test_Ajax_Action (T : in out Test); -- Test a POST request to invoke a bean method. -- Verify that invalid requests raise an error. procedure Test_Ajax_Action_Error (T : in out Test); -- Test a POST/REDIRECT/GET request with a flash information passed in between. procedure Test_Flash_Object (T : in out Test); -- Test a GET+POST request with the default navigation rule based on the outcome. procedure Test_Default_Navigation_Rule (T : in out Test); -- Test a GET request with meta data and view parameters. procedure Test_View_Params (T : in out Test); -- Test a GET request with meta data and view action. procedure Test_View_Action (T : in out Test); type Form_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Name : Unbounded_String; Password : Unbounded_String; Email : Unbounded_String; Called : Natural := 0; Gender : Unbounded_String; Use_Flash : Boolean := False; Def_Nav : Boolean := False; Perm_Error : Boolean := False; end record; type Form_Bean_Access is access all Form_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Form_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Form_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Action to save the form procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String); -- Create a form bean. function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; -- Create a list of forms. package Form_Lists is new Util.Beans.Basic.Lists (Form_Bean); -- Create a list of forms. function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access; -- Initialize the ASF application for the unit test. procedure Initialize_Test_Application; end ASF.Applications.Tests;
----------------------------------------------------------------------- -- asf-applications-tests - ASF Application tests using ASFUnit -- 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.Tests; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Util.Beans.Basic.Lists; with Ada.Strings.Unbounded; package ASF.Applications.Tests is use Ada.Strings.Unbounded; Test_Exception : exception; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Initialize the test application overriding procedure Set_Up (T : in out Test); -- Test a GET request on a static file served by the File_Servlet. procedure Test_Get_File (T : in out Test); -- Test a GET 404 error on missing static file served by the File_Servlet. procedure Test_Get_404 (T : in out Test); -- Test a GET request on the measure servlet procedure Test_Get_Measures (T : in out Test); -- Test an invalid HTTP request. procedure Test_Invalid_Request (T : in out Test); -- Test a GET+POST request with submitted values and an action method called on the bean. procedure Test_Form_Post (T : in out Test); -- Test a POST request with an invalid submitted value procedure Test_Form_Post_Validation_Error (T : in out Test); -- Test a GET+POST request with form having <h:selectOneMenu> element. procedure Test_Form_Post_Select (T : in out Test); -- Test a POST request to invoke a bean method. procedure Test_Ajax_Action (T : in out Test); -- Test a POST request to invoke a bean method. -- Verify that invalid requests raise an error. procedure Test_Ajax_Action_Error (T : in out Test); -- Test a POST/REDIRECT/GET request with a flash information passed in between. procedure Test_Flash_Object (T : in out Test); -- Test a GET+POST request with the default navigation rule based on the outcome. procedure Test_Default_Navigation_Rule (T : in out Test); -- Test a GET request with meta data and view parameters. procedure Test_View_Params (T : in out Test); -- Test a GET request with meta data and view action. procedure Test_View_Action (T : in out Test); -- Test a GET request with pretty URL and request parameter injection. procedure Test_View_Inject_Parameter (T : in out Test); type Form_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Name : Unbounded_String; Password : Unbounded_String; Email : Unbounded_String; Called : Natural := 0; Gender : Unbounded_String; Use_Flash : Boolean := False; Def_Nav : Boolean := False; Perm_Error : Boolean := False; end record; type Form_Bean_Access is access all Form_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Form_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Form_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Form_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Action to save the form procedure Save (Data : in out Form_Bean; Outcome : in out Unbounded_String); -- Create a form bean. function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; -- Create a list of forms. package Form_Lists is new Util.Beans.Basic.Lists (Form_Bean); -- Create a list of forms. function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access; -- Initialize the ASF application for the unit test. procedure Initialize_Test_Application; end ASF.Applications.Tests;
Declare the Test_View_Inject_Parameter unit test
Declare the Test_View_Inject_Parameter unit test
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
3d274438ed908abea18b38d423b1b69511f7fa2d
orka_types/src/orka.ads
orka_types/src/orka.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C; package Orka is pragma Pure; type Index_Homogeneous is (X, Y, Z, W); subtype Index_2D is Index_Homogeneous range X .. Y; subtype Index_3D is Index_Homogeneous range X .. Z; ---------------------------------------------------------------------------- type Integer_16 is new Interfaces.C.short; type Integer_32 is new Interfaces.C.int; type Integer_64 is range -(2 ** 63) .. +(2 ** 63 - 1); -- Based on C99 long long int subtype Size is Integer_32 range 0 .. Integer_32'Last; ---------------------------------------------------------------------------- type Unsigned_32 is mod 2 ** 32 with Size => 32; type Unsigned_64 is mod 2 ** 64 with Size => 64; -- Based on C99 unsigned long long int ---------------------------------------------------------------------------- subtype Float_16 is Integer_16; -- F16C extension can be used to convert from/to Single type Float_32 is new Interfaces.C.C_float; type Float_64 is new Interfaces.C.double; overriding function "=" (Left, Right : Float_32) return Boolean; overriding function "=" (Left, Right : Float_64) return Boolean; ---------------------------------------------------------------------------- type Time is private; function "-" (Left, Right : Time) return Duration; function "-" (Left : Time; Right : Duration) return Time; private overriding function "=" (Left, Right : Float_32) return Boolean is (abs (Left - Right) <= Float_32'Model_Epsilon); overriding function "=" (Left, Right : Float_64) return Boolean is (abs (Left - Right) <= Float_64'Model_Epsilon); type Time is new Duration; function "-" (Left, Right : Time) return Duration is (Duration (Left) - Duration (Right)); function "-" (Left : Time; Right : Duration) return Time is (Time (Duration (Left) - Right)); end Orka;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C; package Orka is pragma Pure; type Index_4D is (X, Y, Z, W); subtype Index_2D is Index_4D range X .. Y; subtype Index_3D is Index_4D range X .. Z; ---------------------------------------------------------------------------- type Integer_16 is new Interfaces.C.short; type Integer_32 is new Interfaces.C.int; type Integer_64 is range -(2 ** 63) .. +(2 ** 63 - 1); -- Based on C99 long long int subtype Size is Integer_32 range 0 .. Integer_32'Last; ---------------------------------------------------------------------------- type Unsigned_32 is mod 2 ** 32 with Size => 32; type Unsigned_64 is mod 2 ** 64 with Size => 64; -- Based on C99 unsigned long long int ---------------------------------------------------------------------------- subtype Float_16 is Integer_16; -- F16C extension can be used to convert from/to Single type Float_32 is new Interfaces.C.C_float; type Float_64 is new Interfaces.C.double; overriding function "=" (Left, Right : Float_32) return Boolean; overriding function "=" (Left, Right : Float_64) return Boolean; ---------------------------------------------------------------------------- type Time is private; function "-" (Left, Right : Time) return Duration; function "-" (Left : Time; Right : Duration) return Time; private overriding function "=" (Left, Right : Float_32) return Boolean is (abs (Left - Right) <= Float_32'Model_Epsilon); overriding function "=" (Left, Right : Float_64) return Boolean is (abs (Left - Right) <= Float_64'Model_Epsilon); type Time is new Duration; function "-" (Left, Right : Time) return Duration is (Duration (Left) - Duration (Right)); function "-" (Left : Time; Right : Duration) return Time is (Time (Duration (Left) - Right)); end Orka;
Rename type Index_Homogeneous to Index_4D
orka: Rename type Index_Homogeneous to Index_4D A vector is a homogeneous coordinate if the W component is 1.0. Type Index_Homogeneous is just an enumeration type, thus it makes more sense to give it the shorter name Index_4D. Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
4d1ba09674e37e4f9b4030692ff4b9efb4eb0bc8
src/sqlite/ado-drivers-connections-sqlite.adb
src/sqlite/ado-drivers-connections-sqlite.adb
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with ADO.Sessions; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Rollback; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin Log.Info ("Close connection {0}", Database.Name); Database.Server := null; end Close; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; protected body Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is use Strings; URI : constant String := Config.Get_URI; Database : Database_Connection_Access; Pos : Database_List.Cursor := Database_List.First (List); DB : SQLite_Database; begin -- Look first in the database list. while Database_List.Has_Element (Pos) loop DB := Database_List.Element (Pos); if DB.URI = URI then Database := new Database_Connection; Database.URI := DB.URI; Database.Name := DB.Name; Database.Server := DB.Server; Result := Ref.Create (Database.all'Access); return; end if; Database_List.Next (Pos); end loop; -- Now we can open a new database connection. declare Name : constant String := Config.Get_Database; Filename : Strings.chars_ptr; Status : int; Handle : aliased access Sqlite3; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot open SQLite database: {0}", Msg); raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg; end; end if; Database := new Database_Connection; declare procedure Configure (Name : in String; Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := Util.Properties.To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name : in String; Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item); begin if Util.Strings.Index (Name, '.') = 0 then Log.Info ("Configure database with {0}", SQL); ADO.Statements.Sqlite.Execute (Database.Server, SQL); end if; exception when SQL_Error => null; end Configure; begin Database.Server := Handle; Database.Name := To_Unbounded_String (Config.Get_Database); Database.URI := To_Unbounded_String (URI); Result := Ref.Create (Database.all'Access); DB.Server := Handle; DB.Name := Database.Name; DB.URI := Database.URI; Database_List.Prepend (Container => List, New_Item => DB); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Iterate (Process => Configure'Access); end; end; end Open; procedure Clear is DB : SQLite_Database; Result : int; begin while not Database_List.Is_Empty (List) loop DB := Database_List.First_Element (List); Database_List.Delete_First (List); if DB.Server /= null then Result := Sqlite3_H.sqlite3_close_v2 (DB.Server); if Result /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot close database {0}: {1}", To_String (DB.Name), Msg); end; end if; end if; end loop; end Clear; end Sqlite_Connections; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin D.Map.Open (Config, Result); end Create_Connection; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. -- ------------------------------ overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (D, Admin); Status : Integer; Database_Path : constant String := Config.Get_Database; Command : constant String := "sqlite3 --batch --init " & Schema_Path & " " & Database_Path; begin Log.Info ("Creating SQLite database {0}", Database_Path); Util.Processes.Tools.Execute (Command, Messages, Status); if Status = 0 then Log.Info ("Database schema created successfully."); elsif Status = 255 then Messages.Append ("Command not found: " & Command); Log.Error ("Command not found: {0}", Command); else Messages.Append ("Command " & Command & " failed with exit code " & Util.Strings.Image (Status)); Log.Error ("Command {0} failed with exit code {1}", Command, Util.Strings.Image (Status)); end if; end Create_Database; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the SQLite driver. -- ------------------------------ overriding procedure Finalize (D : in out Sqlite_Driver) is begin Log.Debug ("Deleting the sqlite driver"); D.Map.Clear; end Finalize; end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with ADO.Sessions; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin if Database.Server = null then raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; end Rollback; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin Log.Info ("Close connection {0}", Database.Name); Database.Server := null; end Close; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; protected body Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is use Strings; URI : constant String := Config.Get_URI; Database : Database_Connection_Access; Pos : Database_List.Cursor := Database_List.First (List); DB : SQLite_Database; begin -- Look first in the database list. while Database_List.Has_Element (Pos) loop DB := Database_List.Element (Pos); if DB.URI = URI then Database := new Database_Connection; Database.URI := DB.URI; Database.Name := DB.Name; Database.Server := DB.Server; Result := Ref.Create (Database.all'Access); return; end if; Database_List.Next (Pos); end loop; -- Now we can open a new database connection. declare Name : constant String := Config.Get_Database; Filename : Strings.chars_ptr; Status : int; Handle : aliased access Sqlite3; Flags : int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin if Config.Get_Property ("create") = "1" then Flags := Flags + Sqlite3_H.SQLITE_OPEN_CREATE; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Status); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot open SQLite database: {0}", Msg); raise ADO.Configs.Connection_Error with "Cannot open database: " & Msg; end; end if; Database := new Database_Connection; declare procedure Configure (Name : in String; Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := Util.Properties.To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name : in String; Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item); begin if Util.Strings.Index (Name, '.') = 0 then Log.Info ("Configure database with {0}", SQL); ADO.Statements.Sqlite.Execute (Database.Server, SQL); end if; exception when SQL_Error => null; end Configure; begin Database.Server := Handle; Database.Name := To_Unbounded_String (Config.Get_Database); Database.URI := To_Unbounded_String (URI); Result := Ref.Create (Database.all'Access); DB.Server := Handle; DB.Name := Database.Name; DB.URI := Database.URI; Database_List.Prepend (Container => List, New_Item => DB); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Iterate (Process => Configure'Access); end; end; end Open; procedure Clear is DB : SQLite_Database; Result : int; begin while not Database_List.Is_Empty (List) loop DB := Database_List.First_Element (List); Database_List.Delete_First (List); if DB.Server /= null then Result := Sqlite3_H.sqlite3_close_v2 (DB.Server); if Result /= Sqlite3_H.SQLITE_OK then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errstr (Result); Msg : constant String := Strings.Value (Error); begin Log.Error ("Cannot close database {0}: {1}", To_String (DB.Name), Msg); end; end if; end if; end loop; end Clear; end Sqlite_Connections; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin D.Map.Open (Config, Result); end Create_Connection; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. -- ------------------------------ overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (D, Admin); Status : Integer; Database_Path : constant String := Config.Get_Database; Command : constant String := "sqlite3 --batch --init " & Schema_Path & " " & Database_Path; begin Log.Info ("Creating SQLite database {0}", Database_Path); Util.Processes.Tools.Execute (Command, Messages, Status); if Status = 0 then Log.Info ("Database schema created successfully."); elsif Status = 255 then Messages.Append ("Command not found: " & Command); Log.Error ("Command not found: {0}", Command); else Messages.Append ("Command " & Command & " failed with exit code " & Util.Strings.Image (Status)); Log.Error ("Command {0} failed with exit code {1}", Command, Util.Strings.Image (Status)); end if; end Create_Database; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the SQLite driver. -- ------------------------------ overriding procedure Finalize (D : in out Sqlite_Driver) is begin Log.Debug ("Deleting the sqlite driver"); D.Map.Clear; end Finalize; end ADO.Drivers.Connections.Sqlite;
Add create property to setup the create flag when opening the SQLite database
Add create property to setup the create flag when opening the SQLite database
Ada
apache-2.0
stcarrez/ada-ado
4e2b00e4093efafcef56f275dd7350fec0fd146f
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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 := '/'; 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, "stat"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "fstat"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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 := '/'; 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); end Util.Systems.Os;
Use the generated system call name for stat() and fstat()
Use the generated system call name for stat() and fstat()
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fd296d4fa4a846f5a8a42c60a7cc60b97ab249ae
src/base/beans/util-beans-objects-vectors.ads
src/base/beans/util-beans-objects-vectors.ads
----------------------------------------------------------------------- -- util-beans-vectors -- Object vectors -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Beans.Basic; package Util.Beans.Objects.Vectors is package Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Object); subtype Cursor is Vectors.Cursor; subtype Vector is Vectors.Vector; -- Make all the Vectors operations available (a kind of 'use Vectors' for anybody). function Length (Container : in Vector) return Ada.Containers.Count_Type renames Vectors.Length; function Is_Empty (Container : in Vector) return Boolean renames Vectors.Is_Empty; procedure Clear (Container : in out Vector) renames Vectors.Clear; function First (Container : in Vector) return Cursor renames Vectors.First; function Last (Container : in Vector) return Cursor renames Vectors.Last; function Element (Container : in Vector; Position : in Natural) return Object renames Vectors.Element; procedure Append (Container : in out Vector; New_Item : in Object; Count : in Ada.Containers.Count_Type := 1) renames Vectors.Append; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Element : Object)) renames Vectors.Query_Element; procedure Update_Element (Container : in out Vector; Position : in Cursor; Process : not null access procedure (Element : in out Object)) renames Vectors.Update_Element; function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element; function Element (Position : Cursor) return Object renames Vectors.Element; procedure Next (Position : in out Cursor) renames Vectors.Next; function Next (Position : Cursor) return Cursor renames Vectors.Next; function Previous (Position : Cursor) return Cursor renames Vectors.Previous; procedure Previous (Position : in out Cursor) renames Vectors.Previous; -- ------------------------------ -- Map Bean -- ------------------------------ -- The <b>Map_Bean</b> is a map of objects that also exposes the <b>Bean</b> interface. -- This allows the map to be available and accessed from an Object instance. type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean with private; type Vector_Bean_Access is access all Vector_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Vector_Bean; Name : in String) return Object; -- Get the number of elements in the list. overriding function Get_Count (From : in Vector_Bean) return Natural; -- Get the element at the given position. overriding function Get_Row (From : in Vector_Bean; Position : in Natural) return Util.Beans.Objects.Object; -- Create an object that contains a <tt>Vector_Bean</tt> instance. function Create return Object; private type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean with null record; end Util.Beans.Objects.Vectors;
----------------------------------------------------------------------- -- util-beans-vectors -- Object vectors -- Copyright (C) 2011, 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.Containers.Vectors; with Util.Beans.Basic; -- == Object vectors == -- The `Util.Beans.Objects.Vectors` package provides a vector of objects. -- To create an instance of the vector, it is possible to use the `Create` function -- as follows: -- -- List : Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Create; -- package Util.Beans.Objects.Vectors is package Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Object); subtype Cursor is Vectors.Cursor; subtype Vector is Vectors.Vector; -- Make all the Vectors operations available (a kind of 'use Vectors' for anybody). function Length (Container : in Vector) return Ada.Containers.Count_Type renames Vectors.Length; function Is_Empty (Container : in Vector) return Boolean renames Vectors.Is_Empty; procedure Clear (Container : in out Vector) renames Vectors.Clear; function First (Container : in Vector) return Cursor renames Vectors.First; function Last (Container : in Vector) return Cursor renames Vectors.Last; function Element (Container : in Vector; Position : in Natural) return Object renames Vectors.Element; procedure Append (Container : in out Vector; New_Item : in Object; Count : in Ada.Containers.Count_Type := 1) renames Vectors.Append; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Element : Object)) renames Vectors.Query_Element; procedure Update_Element (Container : in out Vector; Position : in Cursor; Process : not null access procedure (Element : in out Object)) renames Vectors.Update_Element; function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element; function Element (Position : Cursor) return Object renames Vectors.Element; procedure Next (Position : in out Cursor) renames Vectors.Next; function Next (Position : Cursor) return Cursor renames Vectors.Next; function Previous (Position : Cursor) return Cursor renames Vectors.Previous; procedure Previous (Position : in out Cursor) renames Vectors.Previous; -- ------------------------------ -- Vector Bean -- ------------------------------ -- The `Vector_Bean` is a vector of objects that also exposes the <b>Bean</b> interface. -- This allows the vector to be available and accessed from an Object instance. type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean with private; type Vector_Bean_Access is access all Vector_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Vector_Bean; Name : in String) return Object; -- Get the number of elements in the list. overriding function Get_Count (From : in Vector_Bean) return Natural; -- Get the element at the given position. overriding function Get_Row (From : in Vector_Bean; Position : in Natural) return Util.Beans.Objects.Object; -- Create an object that contains a `Vector_Bean` instance. function Create return Object; -- Iterate over the vectors or array elements. -- If the object is not a `Vector_Bean` or an array, the operation does nothing. procedure Iterate (From : in Object; Process : not null access procedure (Item : in Object)); private type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean with null record; end Util.Beans.Objects.Vectors;
Declare the Iterate procedure and add some documentation
Declare the Iterate procedure and add some documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
535c4e1d12cd1d97a69c2db598904f6e528b6f51
src/core/util-locales.adb
src/core/util-locales.adb
----------------------------------------------------------------------- -- util-locales -- Locale support -- Copyright (C) 2001, 2002, 2003, 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 Ada.Strings.Hash; package body Util.Locales is -- ------------------------------ -- Get the lowercase two-letter ISO-639 code. -- ------------------------------ function Get_Language (Loc : in Locale) return String is begin if Loc = null then return ""; else return Loc (1 .. 2); end if; end Get_Language; -- ------------------------------ -- Get the ISO 639-2 language code. -- ------------------------------ function Get_ISO3_Language (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 3 then return ""; end if; if Loc'Length <= 6 then return Loc (4 .. 6); end if; return Loc (7 .. 9); end Get_ISO3_Language; -- ------------------------------ -- Get the uppercase two-letter ISO-3166 code. -- ------------------------------ function Get_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 2 or else Loc (3) /= '_' then return ""; else return Loc (4 .. 5); end if; end Get_Country; -- ------------------------------ -- Get the ISO-3166-2 country code. -- ------------------------------ function Get_ISO3_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 5 then return ""; else return Loc (10 .. Loc'Last); end if; end Get_ISO3_Country; -- ------------------------------ -- Get the variant code -- ------------------------------ function Get_Variant (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 13 then return ""; else return Loc (7 .. 8); end if; end Get_Variant; -- ------------------------------ -- Get the locale for the given language code -- ------------------------------ function Get_Locale (Language : in String) return Locale is Length : constant Natural := Language'Length; Lower : Natural := Locales'First; Upper : Natural := Locales'Last; Pos : Natural; Result : Locale; begin while Lower <= Upper loop Pos := (Lower + Upper) / 2; Result := Locales (Pos); if Result'Length < Length then if Result.all < Language (Language'First .. Language'First + Result'Length - 1) then Lower := Pos + 1; else Upper := Pos - 1; end if; elsif Result'Length > Length and then Result (Length + 1) = '.' and then Result (1 .. Length) = Language then return Result; elsif Result (1 .. Length) < Language then Lower := Pos + 1; else Upper := Pos - 1; end if; end loop; return NULL_LOCALE; end Get_Locale; -- ------------------------------ -- Get the locale for the given language and country code -- ------------------------------ function Get_Locale (Language : in String; Country : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) then return NULL_LOCALE; elsif Country'Length = 0 then return Get_Locale (Language); else return Get_Locale (Language & "_" & Country); end if; end Get_Locale; -- ------------------------------ -- Get the locale for the given language, country and variant code -- ------------------------------ function Get_Locale (Language : in String; Country : in String; Variant : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) or else (Variant'Length /= 0 and Variant'Length /= 2) then return NULL_LOCALE; end if; if Country'Length = 0 and Variant'Length = 0 then return Get_Locale (Language); elsif Variant'Length = 0 then return Get_Locale (Language, Country); else return Get_Locale (Language & "_" & Country & "_" & Variant); end if; end Get_Locale; -- ------------------------------ -- Get the locale code in the form <i>language</i>_<i>country</i>_<i>variant</i>. -- ------------------------------ function To_String (Loc : in Locale) return String is begin if Loc = null then return ""; elsif Loc'Length > 3 and Loc (3) = '.' then return Loc (1 .. 2); elsif Loc'Length > 6 and Loc (6) = '.' then return Loc (1 .. 5); else return Loc (1 .. 8); end if; end To_String; -- ------------------------------ -- Compute the hash value of the locale. -- ------------------------------ function Hash (Loc : in Locale) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Loc.all); end Hash; end Util.Locales;
----------------------------------------------------------------------- -- util-locales -- Locale support -- Copyright (C) 2001 - 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.Hash; package body Util.Locales is -- ------------------------------ -- Get the lowercase two-letter ISO-639 code. -- ------------------------------ function Get_Language (Loc : in Locale) return String is begin if Loc = null then return ""; else return Loc (1 .. 2); end if; end Get_Language; -- ------------------------------ -- Get the ISO 639-2 language code. -- ------------------------------ function Get_ISO3_Language (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 3 then return ""; end if; if Loc'Length <= 6 then return Loc (4 .. 6); end if; if Loc'Length <= 13 then return Loc (7 .. 9); end if; return Loc (10 .. 15); end Get_ISO3_Language; -- ------------------------------ -- Get the uppercase two-letter ISO-3166 code. -- ------------------------------ function Get_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 2 or else Loc (3) /= '_' then return ""; else return Loc (4 .. 5); end if; end Get_Country; -- ------------------------------ -- Get the ISO-3166-2 country code. -- ------------------------------ function Get_ISO3_Country (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 9 then return ""; else return Loc (Loc'Last - 2 .. Loc'Last); end if; end Get_ISO3_Country; -- ------------------------------ -- Get the variant code -- ------------------------------ function Get_Variant (Loc : in Locale) return String is begin if Loc = null or else Loc'Length <= 13 then return ""; else return Loc (7 .. 8); end if; end Get_Variant; -- ------------------------------ -- Get the locale for the given language code -- ------------------------------ function Get_Locale (Language : in String) return Locale is Length : constant Natural := Language'Length; Lower : Natural := Locales'First; Upper : Natural := Locales'Last; Pos : Natural; Result : Locale; begin while Lower <= Upper loop Pos := (Lower + Upper) / 2; Result := Locales (Pos); if Result'Length < Length then if Result.all < Language (Language'First .. Language'First + Result'Length - 1) then Lower := Pos + 1; else Upper := Pos - 1; end if; elsif Result'Length > Length and then Result (Length + 1) = '.' and then Result (1 .. Length) = Language then return Result; elsif Result (1 .. Length) < Language then Lower := Pos + 1; else Upper := Pos - 1; end if; end loop; return NULL_LOCALE; end Get_Locale; -- ------------------------------ -- Get the locale for the given language and country code -- ------------------------------ function Get_Locale (Language : in String; Country : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) then return NULL_LOCALE; elsif Country'Length = 0 then return Get_Locale (Language); else return Get_Locale (Language & "_" & Country); end if; end Get_Locale; -- ------------------------------ -- Get the locale for the given language, country and variant code -- ------------------------------ function Get_Locale (Language : in String; Country : in String; Variant : in String) return Locale is begin if Language'Length /= 2 or else (Country'Length /= 0 and Country'Length /= 2) or else (Variant'Length /= 0 and Variant'Length /= 2) then return NULL_LOCALE; end if; if Country'Length = 0 and Variant'Length = 0 then return Get_Locale (Language); elsif Variant'Length = 0 then return Get_Locale (Language, Country); else return Get_Locale (Language & "_" & Country & "_" & Variant); end if; end Get_Locale; -- ------------------------------ -- Get the locale code in the form <i>language</i>_<i>country</i>_<i>variant</i>. -- ------------------------------ function To_String (Loc : in Locale) return String is begin if Loc = null then return ""; elsif Loc'Length > 3 and Loc (3) = '.' then return Loc (1 .. 2); elsif Loc'Length > 6 and Loc (6) = '.' then return Loc (1 .. 5); else return Loc (1 .. 8); end if; end To_String; -- ------------------------------ -- Compute the hash value of the locale. -- ------------------------------ function Hash (Loc : in Locale) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (Loc.all); end Hash; end Util.Locales;
Fix Get_ISO3_Country and Get_ISO3_Language which were incorrect for some locales
Fix Get_ISO3_Country and Get_ISO3_Language which were incorrect for some locales
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2af423fe0f1b81ff3232d2220116cae039e74317
src/util-encoders.adb
src/util-encoders.adb
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Encoders.Base16; with Util.Encoders.Base64; with Util.Encoders.SHA1; package body Util.Encoders is use Ada; use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; procedure Free is new Ada.Unchecked_Deallocation (Transformer'Class, Transformer_Access); -- ------------------------------ -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. -- ------------------------------ function Encode (E : in Encoder; Data : in String) return String is begin if E.Encode = null then raise Not_Supported with "There is no encoder"; end if; return E.Encode.Transform (Data); end Encode; -- ------------------------------ -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. -- ------------------------------ function Decode (E : in Decoder; Data : in String) return String is begin if E.Decode = null then raise Not_Supported with "There is no decoder"; end if; return E.Decode.Transform (Data); end Decode; MIN_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 64; MAX_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 2_048; function Best_Size (Length : Natural) return Streams.Stream_Element_Offset; pragma Inline (Best_Size); -- ------------------------------ -- Compute a good size for allocating a buffer on the stack -- ------------------------------ function Best_Size (Length : Natural) return Streams.Stream_Element_Offset is begin if Length < Natural (MIN_BUFFER_SIZE) then return MIN_BUFFER_SIZE; elsif Length > Natural (MAX_BUFFER_SIZE) then return MAX_BUFFER_SIZE; else return Streams.Stream_Element_Offset (((Length + 15) / 16) * 16); end if; end Best_Size; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in out Transformer'Class; Data : in String) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural := Data'First; Last : Streams.Stream_Element_Offset; begin while Pos <= Data'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; First_Encoded : Streams.Stream_Element_Offset := 1; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in out result string. loop E.Transform (Data => Buf (First_Encoded .. Size), Into => Res, Encoded => Last_Encoded, Last => Last); -- If the encoder generated nothing, move the position backward -- to take into account the remaining bytes not taken into account. if Last < 1 then Next_Pos := Next_Pos - Natural (Size - First_Encoded + 1); exit; end if; for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); exit when Last_Encoded = Size; First_Encoded := Last_Encoded + 1; end loop; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; Pos := Next_Pos; end; end loop; Last := 0; E.Finish (Into => Res, Last => Last); if Last > 0 then for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); end if; return To_String (Result); end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ procedure Transform (E : in out Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Pos : Natural := Data'First; First : Streams.Stream_Element_Offset := Into'First; begin Last := Into'First - 1; while Pos <= Data'Last and Last < Into'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in the output data array. E.Transform (Data => Buf (1 .. Size), Into => Into (First .. Into'Last), Encoded => Last_Encoded, Last => Last); -- If the encoded has not used all the data, update the position for the next run. if Last_Encoded /= Size then Next_Pos := Next_Pos - Natural (Size - Last_Encoded + 1); end if; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; First := Last; Pos := Next_Pos; end; end loop; if Pos <= Data'Last then raise Encoding_Error with "Not enough space for encoding"; end if; end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in out Transformer'Class; Data : in Streams.Stream_Element_Array) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Last_Encoded : Streams.Stream_Element_Offset; Last : Streams.Stream_Element_Offset; begin -- Encode that buffer and put the result in out result string. E.Transform (Data => Data, Into => Res, Encoded => Last_Encoded, Last => Last); E.Finish (Res (Last + 1 .. Res'Last), Last); for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); return To_String (Result); end Transform; -- ------------------------------ -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. -- ------------------------------ procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; P : Ada.Streams.Stream_Element_Offset := Pos; V, U : Interfaces.Unsigned_64; begin V := Val; loop if V < 16#07F# then Into (P) := Ada.Streams.Stream_Element (V); Last := P; return; end if; U := V and 16#07F#; Into (P) := Ada.Streams.Stream_Element (U or 16#80#); P := P + 1; V := Interfaces.Shift_Right (V, 7); end loop; end Encode_LEB128; -- ------------------------------ -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. -- ------------------------------ procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; use type Interfaces.Unsigned_8; P : Ada.Streams.Stream_Element_Offset := Pos; Value : Interfaces.Unsigned_64 := 0; V : Interfaces.Unsigned_8; Shift : Integer := 0; begin loop V := Interfaces.Unsigned_8 (From (P)); if (V and 16#80#) = 0 then Val := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; Last := P + 1; return; end if; V := V and 16#07F#; Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; P := P + 1; Shift := Shift + 7; end loop; end Decode_LEB128; -- ------------------------------ -- Create the encoder object for the specified algorithm. -- ------------------------------ function Create (Name : String) return Encoder is begin if Name = BASE_16 or Name = HEX then return E : Encoder do E.Encode := new Util.Encoders.Base16.Encoder; end return; elsif Name = BASE_64 then return E : Encoder do E.Encode := new Util.Encoders.Base64.Encoder; end return; elsif Name = BASE_64_URL then return E : Encoder do E.Encode := Util.Encoders.Base64.Create_URL_Encoder; end return; elsif Name = HASH_SHA1 then return E : Encoder do E.Encode := new Util.Encoders.SHA1.Encoder; end return; end if; raise Not_Supported with "Invalid encoder: " & Name; end Create; -- ------------------------------ -- Create the encoder object for the specified algorithm. -- ------------------------------ function Create (Name : String) return Decoder is begin if Name = BASE_16 or Name = HEX then return E : Decoder do E.Decode := new Util.Encoders.Base16.Decoder; end return; elsif Name = BASE_64 then return E : Decoder do E.Decode := new Util.Encoders.Base64.Decoder; end return; elsif Name = BASE_64_URL then return E : Decoder do E.Decode := Util.Encoders.Base64.Create_URL_Decoder; end return; elsif Name = HASH_SHA1 then return E : Decoder do E.Decode := new Util.Encoders.Base64.Decoder; end return; end if; raise Not_Supported with "Invalid encoder: " & Name; end Create; -- ------------------------------ -- Delete the transformers -- ------------------------------ overriding procedure Finalize (E : in out Encoder) is begin Free (E.Encode); end Finalize; -- ------------------------------ -- Delete the transformers -- ------------------------------ overriding procedure Finalize (E : in out Decoder) is begin Free (E.Decode); end Finalize; end Util.Encoders;
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Encoders.Base16; with Util.Encoders.Base64; with Util.Encoders.SHA1; package body Util.Encoders is use Ada; use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; procedure Free is new Ada.Unchecked_Deallocation (Transformer'Class, Transformer_Access); -- ------------------------------ -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. -- ------------------------------ function Encode (E : in Encoder; Data : in String) return String is begin if E.Encode = null then raise Not_Supported with "There is no encoder"; end if; return E.Encode.Transform (Data); end Encode; function Encode (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String is begin if E.Encode = null then raise Not_Supported with "There is no encoder"; end if; return E.Encode.Transform (Data); end Encode; -- ------------------------------ -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. -- ------------------------------ function Decode (E : in Decoder; Data : in String) return String is begin if E.Decode = null then raise Not_Supported with "There is no decoder"; end if; return E.Decode.Transform (Data); end Decode; MIN_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 64; MAX_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 2_048; function Best_Size (Length : Natural) return Streams.Stream_Element_Offset; pragma Inline (Best_Size); -- ------------------------------ -- Compute a good size for allocating a buffer on the stack -- ------------------------------ function Best_Size (Length : Natural) return Streams.Stream_Element_Offset is begin if Length < Natural (MIN_BUFFER_SIZE) then return MIN_BUFFER_SIZE; elsif Length > Natural (MAX_BUFFER_SIZE) then return MAX_BUFFER_SIZE; else return Streams.Stream_Element_Offset (((Length + 15) / 16) * 16); end if; end Best_Size; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in out Transformer'Class; Data : in String) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural := Data'First; Last : Streams.Stream_Element_Offset; begin while Pos <= Data'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; First_Encoded : Streams.Stream_Element_Offset := 1; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in out result string. loop E.Transform (Data => Buf (First_Encoded .. Size), Into => Res, Encoded => Last_Encoded, Last => Last); -- If the encoder generated nothing, move the position backward -- to take into account the remaining bytes not taken into account. if Last < 1 then Next_Pos := Next_Pos - Natural (Size - First_Encoded + 1); exit; end if; for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); exit when Last_Encoded = Size; First_Encoded := Last_Encoded + 1; end loop; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; Pos := Next_Pos; end; end loop; Last := 0; E.Finish (Into => Res, Last => Last); if Last > 0 then for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); end if; return To_String (Result); end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ procedure Transform (E : in out Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Pos : Natural := Data'First; First : Streams.Stream_Element_Offset := Into'First; begin Last := Into'First - 1; while Pos <= Data'Last and Last < Into'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in the output data array. E.Transform (Data => Buf (1 .. Size), Into => Into (First .. Into'Last), Encoded => Last_Encoded, Last => Last); -- If the encoded has not used all the data, update the position for the next run. if Last_Encoded /= Size then Next_Pos := Next_Pos - Natural (Size - Last_Encoded + 1); end if; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; First := Last; Pos := Next_Pos; end; end loop; if Pos <= Data'Last then raise Encoding_Error with "Not enough space for encoding"; end if; end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in out Transformer'Class; Data : in Streams.Stream_Element_Array) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Last_Encoded : Streams.Stream_Element_Offset; Last : Streams.Stream_Element_Offset; begin -- Encode that buffer and put the result in out result string. E.Transform (Data => Data, Into => Res, Encoded => Last_Encoded, Last => Last); E.Finish (Res (Last + 1 .. Res'Last), Last); for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); return To_String (Result); end Transform; -- ------------------------------ -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. -- ------------------------------ procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; P : Ada.Streams.Stream_Element_Offset := Pos; V, U : Interfaces.Unsigned_64; begin V := Val; loop if V < 16#07F# then Into (P) := Ada.Streams.Stream_Element (V); Last := P; return; end if; U := V and 16#07F#; Into (P) := Ada.Streams.Stream_Element (U or 16#80#); P := P + 1; V := Interfaces.Shift_Right (V, 7); end loop; end Encode_LEB128; -- ------------------------------ -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. -- ------------------------------ procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; use type Interfaces.Unsigned_8; P : Ada.Streams.Stream_Element_Offset := Pos; Value : Interfaces.Unsigned_64 := 0; V : Interfaces.Unsigned_8; Shift : Integer := 0; begin loop V := Interfaces.Unsigned_8 (From (P)); if (V and 16#80#) = 0 then Val := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; Last := P + 1; return; end if; V := V and 16#07F#; Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; P := P + 1; Shift := Shift + 7; end loop; end Decode_LEB128; -- ------------------------------ -- Create the encoder object for the specified algorithm. -- ------------------------------ function Create (Name : String) return Encoder is begin if Name = BASE_16 or Name = HEX then return E : Encoder do E.Encode := new Util.Encoders.Base16.Encoder; end return; elsif Name = BASE_64 then return E : Encoder do E.Encode := new Util.Encoders.Base64.Encoder; end return; elsif Name = BASE_64_URL then return E : Encoder do E.Encode := Util.Encoders.Base64.Create_URL_Encoder; end return; elsif Name = HASH_SHA1 then return E : Encoder do E.Encode := new Util.Encoders.SHA1.Encoder; end return; end if; raise Not_Supported with "Invalid encoder: " & Name; end Create; -- ------------------------------ -- Create the encoder object for the specified algorithm. -- ------------------------------ function Create (Name : String) return Decoder is begin if Name = BASE_16 or Name = HEX then return E : Decoder do E.Decode := new Util.Encoders.Base16.Decoder; end return; elsif Name = BASE_64 then return E : Decoder do E.Decode := new Util.Encoders.Base64.Decoder; end return; elsif Name = BASE_64_URL then return E : Decoder do E.Decode := Util.Encoders.Base64.Create_URL_Decoder; end return; elsif Name = HASH_SHA1 then return E : Decoder do E.Decode := new Util.Encoders.Base64.Decoder; end return; end if; raise Not_Supported with "Invalid encoder: " & Name; end Create; -- ------------------------------ -- Delete the transformers -- ------------------------------ overriding procedure Finalize (E : in out Encoder) is begin Free (E.Encode); end Finalize; -- ------------------------------ -- Delete the transformers -- ------------------------------ overriding procedure Finalize (E : in out Decoder) is begin Free (E.Decode); end Finalize; end Util.Encoders;
Implement the Encode function that accepts a Stream_Element_Array as input
Implement the Encode function that accepts a Stream_Element_Array as input
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e2d590f0e544c37bd7411a06c47f11c336568296
tools/druss-commands-devices.ads
tools/druss-commands-devices.ads
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Druss.Commands.Devices is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Do_List (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type); -- Execute a status command to report information about the Bbox. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type); end Druss.Commands.Devices;
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Druss.Commands.Devices is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Do_List (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type); -- Execute a status command to report information about the Bbox. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Context : in out Context_Type); end Druss.Commands.Devices;
Change Help command to accept in out command
Change Help command to accept in out command
Ada
apache-2.0
stcarrez/bbox-ada-api
f8c5a83eae97f4e91ed3009c4a7a9008542e6777
src/security-contexts.ads
src/security-contexts.ads
----------------------------------------------------------------------- -- 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.Finalization; with Util.Strings.Maps; with Security.Permissions; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Permissions.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- 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); -- 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); -- Set the current application and user context. procedure Set_Context (Context : in out Security_Context; Manager : in Security.Permissions.Permission_Manager_Access; Principal : in Security.Permissions.Principal_Access); -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String); -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. function Get_Context (Context : in Security_Context; Name : in String) return String; -- Returns True if a context information was registered under the name <b>Name</b>. function Has_Context (Context : in Security_Context; Name : in String) return Boolean; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private type Permission_Cache is record Perm : Security.Permissions.Permission_Type; Result : Boolean; end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Permissions.Permission_Manager_Access := null; Principal : Security.Permissions.Principal_Access := null; Context : Util.Strings.Maps.Map; end record; end Security.Contexts;
----------------------------------------------------------------------- -- 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.Finalization; with Util.Strings.Maps; with Security.Permissions; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- 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); -- 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); -- Set the current application and user context. procedure Set_Context (Context : in out Security_Context; Manager : in Security.Permissions.Permission_Manager_Access; Principal : in Security.Principal_Access); -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String); -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. function Get_Context (Context : in Security_Context; Name : in String) return String; -- Returns True if a context information was registered under the name <b>Name</b>. function Has_Context (Context : in Security_Context; Name : in String) return Boolean; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private type Permission_Cache is record Perm : Security.Permissions.Permission_Type; Result : Boolean; end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Permissions.Permission_Manager_Access := null; Principal : Security.Principal_Access := null; Context : Util.Strings.Maps.Map; end record; end Security.Contexts;
Use the Principal defined in the Security package
Use the Principal defined in the Security package
Ada
apache-2.0
Letractively/ada-security
e03bd72e18f1907e86d0b47c5aa4e3a11f2a2242
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016, 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 Interfaces; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wiki.Strings.WChar; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := not P.Context.Is_Included; elsif Token = "includeonly" then P.Context.Is_Hidden := P.Context.Is_Included; end if; else End_Element (P, Tag); end if; else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := P.Context.Is_Included; elsif Token = "includeonly" then P.Context.Is_Hidden := not P.Context.Is_Included; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline (Add_Element); Name : Wiki.Strings.BString (64); begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Add_Element (Name); end Parse_Element; use Interfaces; function From_Hex (C : in Character) return Interfaces.Unsigned_8 is (if C >= '0' and C <= '9' then Character'Pos (C) - Character'Pos ('0') elsif C >= 'A' and C <= 'F' then Character'Pos (C) - Character'Pos ('A') + 10 elsif C >= 'a' and C <= 'f' then Character'Pos (C) - Character'Pos ('a') + 10 else raise Constraint_Error); function From_Hex (Value : in String) return Wiki.Strings.WChar is Result : Interfaces.Unsigned_32 := 0; begin for C of Value loop Result := Interfaces.Shift_Left (Result, 4); Result := Result + Interfaces.Unsigned_32 (From_Hex (C)); end loop; return Wiki.Strings.WChar'Val (Result); end From_Hex; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; if Len > 0 and then Name (Name'First) = '#' then if Name (Name'First + 1) >= '0' and then Name (Name'First + 1) <= '9' then begin C := Wiki.Strings.WChar'Val (Natural'Value (Name (Name'First + 1 .. Len))); Parse_Text (P, C); return; exception when Constraint_Error => null; end; elsif Name (Name'First + 1) = 'x' then begin C := From_Hex (Name (Name'First + 2 .. Len)); Parse_Text (P, C); return; exception when Constraint_Error => null; end; end if; end if; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; if Len > 0 and then Len < Name'Last and then C = ';' then Parse_Text (P, ';'); end if; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016, 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 Interfaces; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Skip_Spaces (P); Collect_Attribute_Value (P, Value); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wiki.Strings.WChar; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := not P.Context.Is_Included; elsif Token = "includeonly" then P.Context.Is_Hidden := P.Context.Is_Included; end if; else End_Element (P, Tag); end if; else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Context.Is_Hidden := P.Context.Is_Included; elsif Token = "includeonly" then P.Context.Is_Hidden := not P.Context.Is_Included; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline (Add_Element); Name : Wiki.Strings.BString (64); begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Add_Element (Name); end Parse_Element; use Interfaces; function From_Hex (C : in Character) return Interfaces.Unsigned_8 is (if C >= '0' and C <= '9' then Character'Pos (C) - Character'Pos ('0') elsif C >= 'A' and C <= 'F' then Character'Pos (C) - Character'Pos ('A') + 10 elsif C >= 'a' and C <= 'f' then Character'Pos (C) - Character'Pos ('a') + 10 else raise Constraint_Error); function From_Hex (Value : in String) return Wiki.Strings.WChar is Result : Interfaces.Unsigned_32 := 0; begin for C of Value loop Result := Interfaces.Shift_Left (Result, 4); Result := Result + Interfaces.Unsigned_32 (From_Hex (C)); end loop; return Wiki.Strings.WChar'Val (Result); end From_Hex; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; if Len > 0 and then Name (Name'First) = '#' then if Name (Name'First + 1) >= '0' and then Name (Name'First + 1) <= '9' then begin C := Wiki.Strings.WChar'Val (Natural'Value (Name (Name'First + 1 .. Len))); Parse_Text (P, C); return; exception when Constraint_Error => null; end; elsif Name (Name'First + 1) = 'x' then begin C := From_Hex (Name (Name'First + 2 .. Len)); Parse_Text (P, C); return; exception when Constraint_Error => null; end; end if; end if; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; if Len > 0 and then Len < Name'Last and then C = ';' then Parse_Text (P, ';'); end if; end Parse_Entity; end Wiki.Parsers.Html;
Fix parsing HTML attributes to allow \n after the '='
Fix parsing HTML attributes to allow \n after the '='
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
4c059302ba86aadc6f7a79f51bc4af3005ec29e7
src/gen-artifacts-docs-markdown.adb
src/gen-artifacts-docs-markdown.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Markdown is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin if Line.Kind = L_LIST then Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_LIST_ITEM then Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_START_CODE or Line.Kind = L_END_CODE then if Formatter.Need_NewLine then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, "```"); else if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line.Content); end if; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end Finish_Document; end Gen.Artifacts.Docs.Markdown;
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Markdown is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_NewLine then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line); end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE | L_END_CODE => Formatter.Write_Line (File, "```"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Write_Line (File, "# " & Line.Content); when L_HEADER_2 => Formatter.Write_Line (File, "## " & Line.Content); when L_HEADER_3 => Formatter.Write_Line (File, "### " & Line.Content); when L_HEADER_4 => Formatter.Write_Line (File, "#### " & Line.Content); when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end Finish_Document; end Gen.Artifacts.Docs.Markdown;
Implement the Write_Line procedure Emit a header according to the L_HEADER_X types
Implement the Write_Line procedure Emit a header according to the L_HEADER_X types
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
69e7c0347a92099e5c891c3f3bad37955035cad8
src/base/commands/util-commands-drivers.adb
src/base/commands/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Compute_Size (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor); Column : Ada.Text_IO.Positive_Count := 1; procedure Compute_Size (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin if Column < Name'Length then Column := Name'Length; end if; end Compute_Size; procedure Print (Position : in Command_Maps.Cursor) is Cmd : constant Command_Access := Command_Maps.Element (Position); Name : constant String := Command_Maps.Key (Position); begin Put (" "); Put (Name); if Length (Cmd.Description) > 0 then Set_Col (Column + 7); Put (To_String (Cmd.Description)); end if; New_Line; end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args, Context); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Compute_Size'Access); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command '{0}'", Cmd_Name); raise Not_Found; else Target_Cmd.Help (Cmd_Name, Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Help_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put ("Invalid command"); end if; end; else Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access) is begin Command.Description := Ada.Strings.Unbounded.To_Unbounded_String (Description); Add_Command (Driver, Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler) is Command : constant Command_Access := new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Description => To_Unbounded_String (Description), Handler => Handler); begin Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error ("Unkown command '{0}'", Name); raise Not_Found; end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in out Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Handler_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Get the description associated with the command. -- ------------------------------ function Get_Description (Command : in Command_Type) return String is begin return To_String (Command.Description); end Get_Description; -- ------------------------------ -- Get the name used to register the command. -- ------------------------------ function Get_Name (Command : in Command_Type) return String is begin return To_String (Command.Name); end Get_Name; -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Compute_Size (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor); Column : Ada.Text_IO.Positive_Count := 1; procedure Compute_Size (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin if Column < Name'Length then Column := Name'Length; end if; end Compute_Size; procedure Print (Position : in Command_Maps.Cursor) is Cmd : constant Command_Access := Command_Maps.Element (Position); Name : constant String := Command_Maps.Key (Position); begin Put (" "); Put (Name); if Length (Cmd.Description) > 0 then Set_Col (Column + 7); Put (To_String (Cmd.Description)); end if; New_Line; end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args, Context); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Compute_Size'Access); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command '{0}'", Cmd_Name); raise Not_Found; else Target_Cmd.Help (Cmd_Name, Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Help_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put ("Invalid command"); end if; end; else Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Description := Ada.Strings.Unbounded.To_Unbounded_String (Description); Add_Command (Driver, Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler) is Command : constant Command_Access := new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Description => To_Unbounded_String (Description), Name => To_Unbounded_String (Name), Handler => Handler); begin Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error ("Unkown command '{0}'", Name); raise Not_Found; end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in out Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Handler_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Add Get_Name and Get_Description on Command_Type and record the name when we create a command
Add Get_Name and Get_Description on Command_Type and record the name when we create a command
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4225ddf3fd30459adc26da0dbc19b4e0a49e707a
src/asf-applications-main.adb
src/asf-applications-main.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- 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 ASF.Streams; with ASF.Contexts.Writer; with ASF.Components.Core; with ASF.Components.Core.Factory; with ASF.Components.Html.Factory; with ASF.Components.Utils.Factory; with ASF.Views.Nodes.Core; with ASF.Views.Nodes.Facelets; with EL.Expressions; with EL.Contexts.Default; with Ada.Exceptions; with Ada.Containers.Vectors; package body ASF.Applications.Main is use Util.Log; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main"); -- ------------------------------ -- Get the application view handler. -- ------------------------------ function Get_View_Handler (App : access Application) return access Views.View_Handler'Class is begin return App.View'Unchecked_Access; end Get_View_Handler; -- ------------------------------ -- Initialize the application -- ------------------------------ procedure Initialize (App : in out Application; Conf : in Config) is use ASF.Components; use ASF.Views; begin App.Conf := Conf; App.Set_Init_Parameters (Params => Conf); ASF.Factory.Register (Factory => App.Components, Bindings => Core.Factory.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Html.Factory.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Nodes.Core.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Nodes.Facelets.Definition); ASF.Components.Utils.Factory.Set_Functions (App.Functions); ASF.Views.Nodes.Core.Set_Functions (App.Functions); App.View.Initialize (App.Components'Unchecked_Access, Conf); ASF.Modules.Initialize (App.Modules, Conf); ASF.Locales.Initialize (App.Locales, App.Factory, Conf); end Initialize; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get_Config (App : Application; Param : Config_Param) return String is begin return App.Conf.Get (Param); end Get_Config; -- ------------------------------ -- Set a global variable in the global EL contexts. -- ------------------------------ procedure Set_Global (App : in out Application; Name : in String; Value : in String) is begin App.Set_Global (Name, EL.Objects.To_Object (Value)); end Set_Global; procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object) is begin App.Globals.Bind (Name, Value); end Set_Global; -- ------------------------------ -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. -- ------------------------------ function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Value : constant EL.Expressions.Value_Expression := App.Globals.Get_Variable (Name); begin return Value.Get_Value (Context); end Get_Global; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (App : in out Application; Name : in String; Handler : in Create_Bean_Access; Free : in Free_Bean_Access := null; Scope : in Scope_Type := REQUEST_SCOPE) is begin ASF.Beans.Register (App.Factory, Name, Handler, Free, Scope); end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out EL.Beans.Readonly_Bean_Access; Free : out Free_Bean_Access; Scope : out Scope_Type) is begin ASF.Beans.Create (App.Factory, Name, Result, Free, Scope); end Create; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in ASF.Modules.Module_Access; Name : in String; URI : in String := "") is begin ASF.Modules.Register (App.Modules'Unchecked_Access, Module, Name, URI); Module.Register_Factory (App.Factory); App.View.Register_Module (Module); end Register; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Register (App : in out Application; Name : in String; Bundle : in String) is begin ASF.Locales.Register (App.Locales, App.Factory, Name, Bundle); end Register; -- ------------------------------ -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. -- ------------------------------ procedure Add_Converter (App : in out Application; Name : in String; Converter : access ASF.Converters.Converter'Class) is begin ASF.Factory.Register (Factory => App.Components, Name => Name, Converter => Converter.all'Unchecked_Access); end Add_Converter; -- ------------------------------ -- Closes the application -- ------------------------------ procedure Close (App : in out Application) is begin ASF.Applications.Views.Close (App.View); end Close; type Bean_Object is record Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; end record; package Bean_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Bean_Object); type Bean_Vector_Access is access all Bean_Vectors.Vector; -- ------------------------------ -- Default Resolver -- ------------------------------ type Web_ELResolver is new EL.Contexts.ELResolver with record Request : EL.Contexts.Default.Default_ELResolver_Access; Application : Main.Application_Access; Beans : Bean_Vector_Access; end record; overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object; overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is use EL.Objects; use EL.Beans; use EL.Variables; Result : Object := Resolver.Request.Get_Value (Context, Base, Name); Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access := null; Scope : Scope_Type; begin if not EL.Objects.Is_Null (Result) then return Result; end if; Resolver.Application.Create (Name, Bean, Free, Scope); if Bean = null then return Resolver.Application.Get_Global (Name, Context); -- raise No_Variable -- with "Bean not found: '" & To_String (Name) & "'"; end if; Resolver.Beans.Append (Bean_Object '(Bean, Free)); Result := To_Object (Bean); Resolver.Request.Register (Name, Result); return Result; end Get_Value; -- Set the value associated with a base object and a given property. overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Resolver.Request.Set_Value (Context, Base, Name, Value); end Set_Value; -- ------------------------------ -- Set the current faces context before processing a view. -- ------------------------------ procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access) is begin Context.Get_ELContext.Set_Function_Mapper (App.Functions'Unchecked_Access); ASF.Contexts.Faces.Set_Current (Context, App'Unchecked_Access); end Set_Context; -- ------------------------------ -- Dispatch the request received on a page. -- ------------------------------ procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; use ASF.Applications.Views; use Ada.Exceptions; Writer : aliased ASF.Contexts.Writer.ResponseWriter; Context : aliased ASF.Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Req_Resolver : aliased Default_ELResolver; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Log.Info ("Dispatch {0}", Page); Root_Resolver.Application := App'Unchecked_Access; Root_Resolver.Request := Req_Resolver'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Writer.Initialize ("text/html", "UTF-8", Output); Context.Set_Request (Request'Unchecked_Access); Context.Set_Response (Response'Unchecked_Access); App.Set_Context (Context'Unchecked_Access); begin Handler.Restore_View (Page, Context, View); exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin Handler.Render_View (Context, View); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null and then Bean.Free /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; end Dispatch; -- ------------------------------ -- Dispatch the request received on a page. -- ------------------------------ procedure Postback (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; use ASF.Applications.Views; use Ada.Exceptions; Writer : aliased ASF.Contexts.Writer.ResponseWriter; Context : aliased ASF.Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Req_Resolver : aliased Default_ELResolver; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Log.Info ("Dispatch {0}", Page); Root_Resolver.Application := App'Unchecked_Access; Root_Resolver.Request := Req_Resolver'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Writer.Initialize ("text/html", "UTF-8", Output); Context.Set_Request (Request'Unchecked_Access); Context.Set_Response (Response'Unchecked_Access); App.Set_Context (Context'Unchecked_Access); begin Handler.Restore_View (Page, Context, View); exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin View.Get_Root.Process_Decodes (Context); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin View.Get_Root.Process_Updates (Context); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin Handler.Render_View (Context, View); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null and then Bean.Free /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; end Postback; -- ------------------------------ -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. -- ------------------------------ function Find (App : in Application; Name : in EL.Objects.Object) return access ASF.Converters.Converter'Class is begin return ASF.Factory.Find (App.Components, Name); end Find; -- ------------------------------ -- Register some functions -- ------------------------------ procedure Register_Functions (App : in out Application'Class) is begin Set_Functions (App.Functions); end Register_Functions; end ASF.Applications.Main;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- 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 ASF.Streams; with ASF.Contexts.Writer; with ASF.Components.Core; with ASF.Components.Core.Factory; with ASF.Components.Html.Factory; with ASF.Components.Utils.Factory; with ASF.Views.Nodes.Core; with ASF.Views.Nodes.Facelets; with EL.Expressions; with EL.Contexts.Default; with Ada.Exceptions; with Ada.Containers.Vectors; package body ASF.Applications.Main is use Util.Log; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main"); -- ------------------------------ -- Get the application view handler. -- ------------------------------ function Get_View_Handler (App : access Application) return access Views.View_Handler'Class is begin return App.View'Unchecked_Access; end Get_View_Handler; -- ------------------------------ -- Initialize the application -- ------------------------------ procedure Initialize (App : in out Application; Conf : in Config) is use ASF.Components; use ASF.Views; begin App.Conf := Conf; App.Set_Init_Parameters (Params => Conf); ASF.Factory.Register (Factory => App.Components, Bindings => Core.Factory.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Html.Factory.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Nodes.Core.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Nodes.Facelets.Definition); ASF.Components.Utils.Factory.Set_Functions (App.Functions); ASF.Views.Nodes.Core.Set_Functions (App.Functions); App.View.Initialize (App.Components'Unchecked_Access, Conf); ASF.Modules.Initialize (App.Modules, Conf); ASF.Locales.Initialize (App.Locales, App.Factory, Conf); end Initialize; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get_Config (App : Application; Param : Config_Param) return String is begin return App.Conf.Get (Param); end Get_Config; -- ------------------------------ -- Set a global variable in the global EL contexts. -- ------------------------------ procedure Set_Global (App : in out Application; Name : in String; Value : in String) is begin App.Set_Global (Name, EL.Objects.To_Object (Value)); end Set_Global; procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object) is begin App.Globals.Bind (Name, Value); end Set_Global; -- ------------------------------ -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. -- ------------------------------ function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Value : constant EL.Expressions.Value_Expression := App.Globals.Get_Variable (Name); begin return Value.Get_Value (Context); end Get_Global; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (App : in out Application; Name : in String; Handler : in Create_Bean_Access; Free : in Free_Bean_Access := null; Scope : in Scope_Type := REQUEST_SCOPE) is begin ASF.Beans.Register (App.Factory, Name, Handler, Free, Scope); end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out EL.Beans.Readonly_Bean_Access; Free : out Free_Bean_Access; Scope : out Scope_Type) is begin ASF.Beans.Create (App.Factory, Name, Result, Free, Scope); end Create; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in ASF.Modules.Module_Access; Name : in String; URI : in String := "") is begin ASF.Modules.Register (App.Modules'Unchecked_Access, Module, Name, URI); Module.Register_Factory (App.Factory); App.View.Register_Module (Module); end Register; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Register (App : in out Application; Name : in String; Bundle : in String) is begin ASF.Locales.Register (App.Locales, App.Factory, Name, Bundle); end Register; -- ------------------------------ -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. -- ------------------------------ procedure Add_Converter (App : in out Application; Name : in String; Converter : access ASF.Converters.Converter'Class) is begin ASF.Factory.Register (Factory => App.Components, Name => Name, Converter => Converter.all'Unchecked_Access); end Add_Converter; -- ------------------------------ -- Closes the application -- ------------------------------ procedure Close (App : in out Application) is begin ASF.Applications.Views.Close (App.View); end Close; type Bean_Object is record Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; end record; package Bean_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Bean_Object); type Bean_Vector_Access is access all Bean_Vectors.Vector; -- ------------------------------ -- Default Resolver -- ------------------------------ type Web_ELResolver is new EL.Contexts.ELResolver with record Request : ASF.Requests.Request_Access; Application : Main.Application_Access; Beans : Bean_Vector_Access; end record; overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object; overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is use EL.Objects; use EL.Beans; use EL.Variables; Result : Object; Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access := null; Scope : Scope_Type; Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; Result := Resolver.Request.Get_Attribute (Key); if not EL.Objects.Is_Null (Result) then return Result; end if; Resolver.Application.Create (Name, Bean, Free, Scope); if Bean = null then return Resolver.Application.Get_Global (Name, Context); -- raise No_Variable -- with "Bean not found: '" & To_String (Name) & "'"; end if; Resolver.Beans.Append (Bean_Object '(Bean, Free)); Result := To_Object (Bean); Resolver.Request.Set_Attribute (Key, Result); return Result; end Get_Value; -- Set the value associated with a base object and a given property. overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is pragma Unreferenced (Context); Key : constant String := To_String (Name); begin if Base /= null then Base.Set_Value (Name => Key, Value => Value); else Resolver.Request.Set_Attribute (Name => Key, Value => Value); end if; end Set_Value; -- ------------------------------ -- Set the current faces context before processing a view. -- ------------------------------ procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access) is begin Context.Get_ELContext.Set_Function_Mapper (App.Functions'Unchecked_Access); ASF.Contexts.Faces.Set_Current (Context, App'Unchecked_Access); end Set_Context; -- ------------------------------ -- Dispatch the request received on a page. -- ------------------------------ procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; use ASF.Applications.Views; use Ada.Exceptions; Writer : aliased ASF.Contexts.Writer.ResponseWriter; Context : aliased ASF.Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Log.Info ("Dispatch {0}", Page); Root_Resolver.Application := App'Unchecked_Access; Root_Resolver.Request := Request'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Writer.Initialize ("text/html", "UTF-8", Output); Context.Set_Request (Request'Unchecked_Access); Context.Set_Response (Response'Unchecked_Access); App.Set_Context (Context'Unchecked_Access); begin Handler.Restore_View (Page, Context, View); exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin Handler.Render_View (Context, View); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null and then Bean.Free /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; end Dispatch; -- ------------------------------ -- Dispatch the request received on a page. -- ------------------------------ procedure Postback (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; use ASF.Applications.Views; use Ada.Exceptions; Writer : aliased ASF.Contexts.Writer.ResponseWriter; Context : aliased ASF.Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Log.Info ("Dispatch {0}", Page); Root_Resolver.Application := App'Unchecked_Access; Root_Resolver.Request := Request'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Writer.Initialize ("text/html", "UTF-8", Output); Context.Set_Request (Request'Unchecked_Access); Context.Set_Response (Response'Unchecked_Access); App.Set_Context (Context'Unchecked_Access); begin Handler.Restore_View (Page, Context, View); exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin View.Get_Root.Process_Decodes (Context); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin View.Get_Root.Process_Updates (Context); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin Handler.Render_View (Context, View); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null and then Bean.Free /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; end Postback; -- ------------------------------ -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. -- ------------------------------ function Find (App : in Application; Name : in EL.Objects.Object) return access ASF.Converters.Converter'Class is begin return ASF.Factory.Find (App.Components, Name); end Find; -- ------------------------------ -- Register some functions -- ------------------------------ procedure Register_Functions (App : in out Application'Class) is begin Set_Functions (App.Functions); end Register_Functions; end ASF.Applications.Main;
Store the beans created for the request on the request object by using Set_Attribute and Get_Attribute to retrieve them.
Store the beans created for the request on the request object by using Set_Attribute and Get_Attribute to retrieve them.
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c133bcdf3a56ae5e6f2afdb3294a4e742698af6d
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; private with Wiki.Buffers; private with Util.Stacks; private with Wiki.Nodes; private with Wiki.Html_Parser; -- == Wiki Parsers {#wiki-parsers} == -- The `Wikis.Parsers` package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki `Document` -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- `Set_Syntax` procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- `Add_Filter` procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki `Document` is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The `Parse` procedure is then used to parse either a string content or some stream -- represented by the `Input_Stream` interface. After the `Parse` procedure -- completes, the `Document` instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; subtype Parser_Type is Parser; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- 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 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.UString; 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 Trim_End is (None, Left, Right, Both); type Block; type Content_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Content_Access; Last : Natural := 0; Content : Wiki.Strings.WString (1 .. Len); end record; procedure Next (Content : in out Content_Access; Pos : in out Positive) with Inline_Always; use Wiki.Strings.Wide_Wide_Builders; type Block_Type is record Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH; Level : Natural := 0; Marker : Wiki.Strings.WChar := ' '; Number : Integer := 0; end record; type Parser_State_Type is (State_Html_Doctype, State_Html_Comment, State_Html_Attribute, State_Html_Element); type Block_Access is access all Block_Type; package Block_Stack is new Util.Stacks (Element_Type => Block_Type, Element_Type_Access => Block_Access); type Parser_Handler is access procedure (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access); type Parser is tagged limited record Context : aliased Wiki.Plugins.Plugin_Context; Previous_Syntax : Wiki_Syntax; Document : Wiki.Documents.Document; Parse_Block : Parser_Handler; Parse_Inline : Parser_Handler; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Line_Buffer : Wiki.Buffers.Builder (512); Text_Buffer : Wiki.Buffers.Builder (512); Empty_Line : Boolean := True; Is_Last_Line : Boolean := False; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; In_Table : Boolean := False; Need_Paragraph : Boolean := True; Pending_Paragraph : Boolean := False; 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; Preformat_Column : Natural := 1; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Previous_Tag : Html_Tag := UNKNOWN_TAG; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE; Blocks : Block_Stack.Stack; Previous_Line_Empty : Boolean := False; Header_Level : Natural := 0; Is_Empty_Paragraph : Boolean := True; Pre_Tag_Counter : Natural := 0; -- Pre-format code block Preformat_Fence : Wiki.Strings.WChar; Preformat_Indent : Natural := 0; Preformat_Fcount : Natural := 0; Preformat_Format : Wiki.Strings.BString (32); Html : Wiki.Html_Parser.Parser_Type; end record; -- Read the next wiki input line in the line buffer. procedure Read_Line (Parser : in out Parser_Type'Class; Buffer : out Wiki.Buffers.Buffer_Access); function Is_List_Item (P : in Parser; Level : in Natural) return Boolean; function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access; From : in Positive; Token : in Wiki.Strings.WChar) return Boolean; -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser; Trim : in Trim_End := None); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); procedure Pop_List (P : in out Parser; Level : in Natural; Marker : in Wiki.Strings.WChar); procedure Pop_List (P : in out Parser); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Returns true if we are included from another wiki content. function Is_Included (P : in Parser) 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; procedure Process_Html (P : in out Parser; Kind : in Wiki.Html_Parser.State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); 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 Toggle_Format (P : in out Parser; Format : in Format_Type); -- Parse the beginning or the end of a single character sequence. -- Example: -- _name_ *bold* `code` procedure Parse_Format (P : in out Parser; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Expect : in Wiki.Strings.WChar; Format : in Format_Type); -- Parse the beginning or the end of a double character sequence. -- Example: -- --name-- **bold** ~~strike~~ procedure Parse_Format_Double (P : in out Parser; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Expect : in Wiki.Strings.WChar; Format : in Format_Type); -- Push a new block kind on the block stack. procedure Push_Block (P : in out Parser; Kind : in Wiki.Nodes.Node_Kind; Level : in Integer := 0; Marker : in Wiki.Strings.WChar := ' '; Number : in Integer := 0); -- Pop the current block stack. procedure Pop_Block (P : in out Parser); procedure Pop_All (P : in out Parser); procedure Pop_Block_Until (P : in out Parser; Kind : in Wiki.Nodes.Node_Kind; Level : in Integer); procedure Append_Text (P : in out Parser; Text : in Wiki.Strings.BString; From : in Positive; To : in Positive); NAME_ATTR : aliased constant String := "name"; HREF_ATTR : aliased constant String := "href"; LANG_ATTR : aliased constant String := "lang"; TITLE_ATTR : aliased constant String := "title"; end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; private with Wiki.Buffers; private with Util.Stacks; private with Wiki.Nodes; private with Wiki.Html_Parser; -- == Wiki Parsers {#wiki-parsers} == -- The `Wikis.Parsers` package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki `Document` -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- `Set_Syntax` procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- `Add_Filter` procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki `Document` is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The `Parse` procedure is then used to parse either a string content or some stream -- represented by the `Input_Stream` interface. After the `Parse` procedure -- completes, the `Document` instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; subtype Parser_Type is Parser; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- 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 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.UString; 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 Trim_End is (None, Left, Right, Both); type Block; type Content_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Content_Access; Last : Natural := 0; Content : Wiki.Strings.WString (1 .. Len); end record; procedure Next (Content : in out Content_Access; Pos : in out Positive) with Inline_Always; use Wiki.Strings.Wide_Wide_Builders; type Block_Type is record Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH; Level : Natural := 0; Marker : Wiki.Strings.WChar := ' '; Number : Integer := 0; end record; type Parser_State_Type is (State_Html_Doctype, State_Html_Comment, State_Html_Attribute, State_Html_Element); type Block_Access is access all Block_Type; package Block_Stack is new Util.Stacks (Element_Type => Block_Type, Element_Type_Access => Block_Access); type Parser_Handler is access procedure (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access); type Parser is tagged limited record Context : aliased Wiki.Plugins.Plugin_Context; Previous_Syntax : Wiki_Syntax; Document : Wiki.Documents.Document; Parse_Block : Parser_Handler; Parse_Inline : Parser_Handler; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Line_Buffer : Wiki.Buffers.Builder (512); Text_Buffer : Wiki.Buffers.Builder (512); Empty_Line : Boolean := True; Is_Last_Line : Boolean := False; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; In_Table : Boolean := False; Need_Paragraph : Boolean := True; Pending_Paragraph : Boolean := False; 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; Preformat_Column : Natural := 1; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Previous_Tag : Html_Tag := UNKNOWN_TAG; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE; Blocks : Block_Stack.Stack; Previous_Line_Empty : Boolean := False; Header_Level : Natural := 0; Is_Empty_Paragraph : Boolean := True; Pre_Tag_Counter : Natural := 0; -- Pre-format code block Preformat_Fence : Wiki.Strings.WChar; Preformat_Indent : Natural := 0; Preformat_Fcount : Natural := 0; Preformat_Format : Wiki.Strings.BString (32); Html : Wiki.Html_Parser.Parser_Type; end record; -- Read the next wiki input line in the line buffer. procedure Read_Line (Parser : in out Parser_Type'Class; Buffer : out Wiki.Buffers.Buffer_Access); function Is_List_Item (P : in Parser; Level : in Natural) return Boolean; function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access; From : in Positive; Token : in Wiki.Strings.WChar) return Boolean; -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser; Trim : in Trim_End := None); procedure Flush_Block (Parser : in out Parser_Type); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); procedure Pop_List (P : in out Parser; Level : in Natural; Marker : in Wiki.Strings.WChar); procedure Pop_List (P : in out Parser); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Returns true if we are included from another wiki content. function Is_Included (P : in Parser) 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; procedure Process_Html (P : in out Parser; Kind : in Wiki.Html_Parser.State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); 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 Toggle_Format (P : in out Parser; Format : in Format_Type); -- Parse the beginning or the end of a single character sequence. -- Example: -- _name_ *bold* `code` procedure Parse_Format (P : in out Parser; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Expect : in Wiki.Strings.WChar; Format : in Format_Type); -- Parse the beginning or the end of a double character sequence. -- Example: -- --name-- **bold** ~~strike~~ procedure Parse_Format_Double (P : in out Parser; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Expect : in Wiki.Strings.WChar; Format : in Format_Type); -- Push a new block kind on the block stack. procedure Push_Block (P : in out Parser; Kind : in Wiki.Nodes.Node_Kind; Level : in Integer := 0; Marker : in Wiki.Strings.WChar := ' '; Number : in Integer := 0); -- Pop the current block stack. procedure Pop_Block (P : in out Parser); procedure Pop_All (P : in out Parser); procedure Pop_Block_Until (P : in out Parser; Kind : in Wiki.Nodes.Node_Kind; Level : in Integer); procedure Append_Text (P : in out Parser; Text : in Wiki.Strings.BString; From : in Positive; To : in Positive); NAME_ATTR : aliased constant String := "name"; HREF_ATTR : aliased constant String := "href"; LANG_ATTR : aliased constant String := "lang"; TITLE_ATTR : aliased constant String := "title"; end Wiki.Parsers;
Declare the Flush_Block procedure
Declare the Flush_Block procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b0c2c0e4b2dda29b4a85f3de56d2cba323d2f7c7
src/util-commands-drivers.adb
src/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then -- Usage; New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in Command_Type) is begin null; end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Print (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin Put_Line (" " & Name); end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then -- Usage; New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command {0}", Cmd_Name); else Target_Cmd.Help (Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Help_Command_Type; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler) is begin Driver.List.Include (Name, new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Handler => Handler)); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Execute (Name, Args, Context); else Logs.Error ("Unkown command {0}", Name); end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Handler_Command_Type; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Implement the Set_Usage procedure
Implement the Set_Usage procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6b044f4a4bd73042e4c9766703fe88c73adf70e1
testutil/ahven/util-xunit.adb
testutil/ahven/util-xunit.adb
----------------------------------------------------------------------- -- AUnit utils - Helper for writing unit tests -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Calendar; with Ahven.Listeners.Basic; with Ahven.XML_Runner; with Ahven.Text_Runner; with Util.Tests; package body Util.XUnit is -- ------------------------------ -- Build a message from a string (Adaptation for AUnit API). -- ------------------------------ function Format (S : in String) return Message_String is begin return S; end Format; -- ------------------------------ -- Build a message with the source and line number. -- ------------------------------ function Build_Message (Message : in String; Source : in String; Line : in Natural) return String is L : constant String := Natural'Image (Line); begin return Source & ":" & L (2 .. L'Last) & ": " & Message; end Build_Message; procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class); procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class) is begin Test_Case'Class (T).Run_Test; end Run_Test_Case; overriding procedure Initialize (T : in out Test_Case) is begin Ahven.Framework.Add_Test_Routine (T, Run_Test_Case'Access, "Test case"); end Initialize; -- ------------------------------ -- Return the name of the test case. -- ------------------------------ overriding function Get_Name (T : Test_Case) return String is begin return Test_Case'Class (T).Name; end Get_Name; -- maybe_overriding procedure Assert (T : in Test_Case; Condition : in Boolean; Message : in String := "Test failed"; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; -- ------------------------------ -- Check that the value matches what we expect. -- ------------------------------ procedure Assert (T : in Test; Condition : in Boolean; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; First_Test : Test_Object_Access := null; -- ------------------------------ -- Register a test object in the test suite. -- ------------------------------ procedure Register (T : in Test_Object_Access) is begin T.Next := First_Test; First_Test := T; end Register; -- ------------------------------ -- Report passes, skips, failures, and errors from the result collection. -- ------------------------------ procedure Report_Results (Result : in Ahven.Results.Result_Collection; Time : in Duration) is T_Count : constant Integer := Ahven.Results.Test_Count (Result); F_Count : constant Integer := Ahven.Results.Failure_Count (Result); S_Count : constant Integer := Ahven.Results.Skipped_Count (Result); E_Count : constant Integer := Ahven.Results.Error_Count (Result); begin if F_Count > 0 then Ahven.Text_Runner.Print_Failures (Result, 0); end if; if E_Count > 0 then Ahven.Text_Runner.Print_Errors (Result, 0); end if; Ada.Text_IO.Put_Line ("Tests run:" & Integer'Image (T_Count - S_Count) & ", Failures:" & Integer'Image (F_Count) & ", Errors:" & Integer'Image (E_Count) & ", Skipped:" & Integer'Image (S_Count) & ", Time elapsed:" & Duration'Image (Time)); end Report_Results; -- ------------------------------ -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. -- ------------------------------ procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String; XML : in Boolean; Result : out Status) is pragma Unreferenced (XML, Output); use Ahven.Listeners.Basic; use Ahven.Framework; use Ahven.Results; use type Ada.Calendar.Time; Tests : constant Access_Test_Suite := Suite; T : Test_Object_Access := First_Test; Listener : Ahven.Listeners.Basic.Basic_Listener; Timeout : constant Test_Duration := Test_Duration (Util.Tests.Get_Test_Timeout ("all")); Out_Dir : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Start : Ada.Calendar.Time; begin while T /= null loop Ahven.Framework.Add_Static_Test (Tests.all, T.Test.all); T := T.Next; end loop; Set_Output_Capture (Listener, True); if not Ada.Directories.Exists (Out_Dir) then Ada.Directories.Create_Path (Out_Dir); end if; Start := Ada.Calendar.Clock; Ahven.Framework.Execute (Tests.all, Listener, Timeout); Report_Results (Listener.Main_Result, Ada.Calendar.Clock - Start); Ahven.XML_Runner.Report_Results (Listener.Main_Result, Out_Dir); if (Error_Count (Listener.Main_Result) > 0) or (Failure_Count (Listener.Main_Result) > 0) then Result := Failure; else Result := Success; end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot create file"); Result := Failure; end Harness; end Util.XUnit;
----------------------------------------------------------------------- -- util-xunit - Unit tests on top of AHven -- 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.Directories; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Calendar; with Ahven.Listeners.Basic; with Ahven.XML_Runner; with Ahven.Text_Runner; with Util.Tests; package body Util.XUnit is -- ------------------------------ -- Build a message from a string (Adaptation for AUnit API). -- ------------------------------ function Format (S : in String) return Message_String is begin return S; end Format; -- ------------------------------ -- Build a message with the source and line number. -- ------------------------------ function Build_Message (Message : in String; Source : in String; Line : in Natural) return String is L : constant String := Natural'Image (Line); begin return Source & ":" & L (2 .. L'Last) & ": " & Message; end Build_Message; procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class); procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class) is begin Test_Case'Class (T).Run_Test; end Run_Test_Case; overriding procedure Initialize (T : in out Test_Case) is begin Ahven.Framework.Add_Test_Routine (T, Run_Test_Case'Access, "Test case"); end Initialize; -- ------------------------------ -- Return the name of the test case. -- ------------------------------ overriding function Get_Name (T : Test_Case) return String is begin return Test_Case'Class (T).Name; end Get_Name; -- maybe_overriding procedure Assert (T : in Test_Case; Condition : in Boolean; Message : in String := "Test failed"; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; -- ------------------------------ -- Check that the value matches what we expect. -- ------------------------------ procedure Assert (T : in Test; Condition : in Boolean; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; First_Test : Test_Object_Access := null; -- ------------------------------ -- Register a test object in the test suite. -- ------------------------------ procedure Register (T : in Test_Object_Access) is begin T.Next := First_Test; First_Test := T; end Register; -- ------------------------------ -- Report passes, skips, failures, and errors from the result collection. -- ------------------------------ procedure Report_Results (Result : in Ahven.Results.Result_Collection; Time : in Duration) is T_Count : constant Integer := Ahven.Results.Test_Count (Result); F_Count : constant Integer := Ahven.Results.Failure_Count (Result); S_Count : constant Integer := Ahven.Results.Skipped_Count (Result); E_Count : constant Integer := Ahven.Results.Error_Count (Result); begin if F_Count > 0 then Ahven.Text_Runner.Print_Failures (Result, 0); end if; if E_Count > 0 then Ahven.Text_Runner.Print_Errors (Result, 0); end if; Ada.Text_IO.Put_Line ("Tests run:" & Integer'Image (T_Count - S_Count) & ", Failures:" & Integer'Image (F_Count) & ", Errors:" & Integer'Image (E_Count) & ", Skipped:" & Integer'Image (S_Count) & ", Time elapsed:" & Duration'Image (Time)); end Report_Results; -- ------------------------------ -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. -- ------------------------------ procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String; XML : in Boolean; Result : out Status) is pragma Unreferenced (XML, Output); use Ahven.Listeners.Basic; use Ahven.Framework; use Ahven.Results; use type Ada.Calendar.Time; Tests : constant Access_Test_Suite := Suite; T : Test_Object_Access := First_Test; Listener : Ahven.Listeners.Basic.Basic_Listener; Timeout : constant Test_Duration := Test_Duration (Util.Tests.Get_Test_Timeout ("all")); Out_Dir : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Start : Ada.Calendar.Time; begin while T /= null loop Ahven.Framework.Add_Static_Test (Tests.all, T.Test.all); T := T.Next; end loop; Set_Output_Capture (Listener, True); if not Ada.Directories.Exists (Out_Dir) then Ada.Directories.Create_Path (Out_Dir); end if; Start := Ada.Calendar.Clock; Ahven.Framework.Execute (Tests.all, Listener, Timeout); Report_Results (Listener.Main_Result, Ada.Calendar.Clock - Start); Ahven.XML_Runner.Report_Results (Listener.Main_Result, Out_Dir); if (Error_Count (Listener.Main_Result) > 0) or (Failure_Count (Listener.Main_Result) > 0) then Result := Failure; else Result := Success; end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot create file"); Result := Failure; end Harness; end Util.XUnit;
Update header comment
Update header comment
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f123af4fb8bb411021a19e8d366549e4d8c04e29
arch/ARM/cortex_m/src/nvic_cm4_cm7/cortex_m-nvic.adb
arch/ARM/cortex_m/src/nvic_cm4_cm7/cortex_m-nvic.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, 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 STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f4xx_hal_cortex.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief CORTEX HAL module driver. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ with Memory_Barriers; package body Cortex_M.NVIC is ----------------------- -- Priority_Grouping -- ----------------------- function Priority_Grouping return UInt32 is begin return Shift_Right (SCB.AIRCR and SCB_AIRCR_PRIGROUP_Mask, SCB_AIRCR_PRIGROUP_Pos); end Priority_Grouping; --------------------------- -- Set_Priority_Grouping -- --------------------------- procedure Set_Priority_Grouping (Priority_Group : UInt32) is Reg_Value : UInt32; PriorityGroupTmp : constant UInt32 := Priority_Group and 16#07#; Key : constant := 16#5FA#; begin Reg_Value := SCB.AIRCR; Reg_Value := Reg_Value and (not (SCB_AIRCR_VECTKEY_Mask or SCB_AIRCR_PRIGROUP_Mask)); Reg_Value := Reg_Value or Shift_Left (Key, SCB_AIRCR_VECTKEY_Pos) or Shift_Left (PriorityGroupTmp, 8); SCB.AIRCR := Reg_Value; end Set_Priority_Grouping; ------------------ -- Set_Priority -- ------------------ procedure Set_Priority (IRQn : Interrupt_ID; Priority : UInt32) is Index : constant Natural := Integer (IRQn); Value : constant UInt32 := Shift_Left (Priority, 8 - NVIC_PRIO_BITS) and 16#FF#; begin -- IRQ numbers are never less than 0 in the current definition, hence -- the code is different from that in the CMSIS. NVIC.IP (Index) := UInt8 (Value); end Set_Priority; ---------------------- -- Encoded_Priority -- ---------------------- function Encoded_Priority (Priority_Group : UInt32; Preempt_Priority : UInt32; Subpriority : UInt32) return UInt32 is PriorityGroupTmp : constant UInt32 := Priority_Group and 16#07#; PreemptPriorityBits : UInt32; SubPriorityBits : UInt32; Temp1 : UInt32; Temp2 : UInt32; Temp3 : UInt32; Temp4 : UInt32; Temp5 : UInt32; begin if (7 - PriorityGroupTmp) > NVIC_PRIO_BITS then PreemptPriorityBits := NVIC_PRIO_BITS; else PreemptPriorityBits := 7 - PriorityGroupTmp; end if; if (PriorityGroupTmp + NVIC_PRIO_BITS) < 7 then SubPriorityBits := 0; else SubPriorityBits := PriorityGroupTmp - 7 + NVIC_PRIO_BITS; end if; Temp1 := Shift_Left (1, Integer (PreemptPriorityBits)) - 1; Temp2 := Preempt_Priority and Temp1; Temp3 := Shift_Left (Temp2, Integer (SubPriorityBits)); Temp4 := Shift_Left (1, Integer (SubPriorityBits)) - 1; Temp5 := Subpriority and Temp4; return Temp3 or Temp5; end Encoded_Priority; ------------------ -- Set_Priority -- ------------------ procedure Set_Priority (IRQn : Interrupt_ID; Preempt_Priority : UInt32; Subpriority : UInt32) is Priority_Group : constant UInt32 := Priority_Grouping; begin Set_Priority (IRQn, Encoded_Priority (Priority_Group, Preempt_Priority, Subpriority)); end Set_Priority; ---------------------- -- Enable_Interrupt -- ---------------------- procedure Enable_Interrupt (IRQn : Interrupt_ID) is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); begin NVIC.ISER (Index) := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); end Enable_Interrupt; ----------------------- -- Disable_Interrupt -- ----------------------- procedure Disable_Interrupt (IRQn : Interrupt_ID) is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); begin -- NVIC->ICER[((uint32_t)(IRQn)>>5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); NVIC.ICER (Index) := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); end Disable_Interrupt; ------------ -- Active -- ------------ function Active (IRQn : Interrupt_ID) return Boolean is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); Value : constant UInt32 := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); begin return (NVIC.IABR (Index) and Value) /= 0; end Active; ------------- -- Pending -- ------------- function Pending (IRQn : Interrupt_ID) return Boolean is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); Value : constant UInt32 := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); begin return (NVIC.ISPR (Index) and Value) /= 0; end Pending; ----------------- -- Set_Pending -- ----------------- procedure Set_Pending (IRQn : Interrupt_ID) is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); begin NVIC.ISPR (Index) := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); end Set_Pending; ------------------- -- Clear_Pending -- ------------------- procedure Clear_Pending (IRQn : Interrupt_ID) is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); begin NVIC.ICPR (Index) := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); end Clear_Pending; ------------------ -- Reset_System -- ------------------ procedure Reset_System is Key : constant := 16#05FA#; -- required for write to be accepted use Memory_Barriers; begin -- Ensure all outstanding memory accesses including -- buffered writes are completed Data_Synchronization_Barrier; SCB.AIRCR := Shift_Left (Key, SCB_AIRCR_VECTKEY_Pos) or -- keep priority group unchanged (SCB.AIRCR and SCB_AIRCR_PRIGROUP_Mask) or SCB_AIRCR_SYSRESETREQ_Mask; -- TODO: why is all code from here onward in the CMSIS??? Data_Synchronization_Barrier; -- wait until reset pragma Warnings (Off); <<spin>> goto spin; pragma Warnings (On); end Reset_System; end Cortex_M.NVIC;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, 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 STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f4xx_hal_cortex.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief CORTEX HAL module driver. -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ with Memory_Barriers; package body Cortex_M.NVIC is ----------------------- -- Priority_Grouping -- ----------------------- function Priority_Grouping return UInt32 is begin return Shift_Right (SCB.AIRCR and SCB_AIRCR_PRIGROUP_Mask, SCB_AIRCR_PRIGROUP_Pos); end Priority_Grouping; --------------------------- -- Set_Priority_Grouping -- --------------------------- procedure Set_Priority_Grouping (Priority_Group : UInt32) is Reg_Value : UInt32; PriorityGroupTmp : constant UInt32 := Priority_Group and 16#07#; Key : constant := 16#5FA#; begin Reg_Value := SCB.AIRCR; Reg_Value := Reg_Value and (not (SCB_AIRCR_VECTKEY_Mask or SCB_AIRCR_PRIGROUP_Mask)); Reg_Value := Reg_Value or Shift_Left (Key, SCB_AIRCR_VECTKEY_Pos) or Shift_Left (PriorityGroupTmp, 8); SCB.AIRCR := Reg_Value; end Set_Priority_Grouping; ------------------ -- Set_Priority -- ------------------ procedure Set_Priority (IRQn : Interrupt_ID; Priority : UInt32) is Index : constant Natural := Integer (IRQn); Value : constant UInt32 := Shift_Left (Priority, 8 - NVIC_PRIO_BITS) and 16#FF#; begin -- IRQ numbers are never less than 0 in the current definition, hence -- the code is different from that in the CMSIS. NVIC.IP (Index) := UInt8 (Value); end Set_Priority; ---------------------- -- Encoded_Priority -- ---------------------- function Encoded_Priority (Priority_Group : UInt32; Preempt_Priority : UInt32; Subpriority : UInt32) return UInt32 is PriorityGroupTmp : constant UInt32 := Priority_Group and 16#07#; PreemptPriorityBits : UInt32; SubPriorityBits : UInt32; Temp1 : UInt32; Temp2 : UInt32; Temp3 : UInt32; Temp4 : UInt32; Temp5 : UInt32; begin if (7 - PriorityGroupTmp) > NVIC_PRIO_BITS then PreemptPriorityBits := NVIC_PRIO_BITS; else PreemptPriorityBits := 7 - PriorityGroupTmp; end if; if (PriorityGroupTmp + NVIC_PRIO_BITS) < 7 then SubPriorityBits := 0; else SubPriorityBits := PriorityGroupTmp - 7 + NVIC_PRIO_BITS; end if; Temp1 := Shift_Left (1, Integer (PreemptPriorityBits)) - 1; Temp2 := Preempt_Priority and Temp1; Temp3 := Shift_Left (Temp2, Integer (SubPriorityBits)); Temp4 := Shift_Left (1, Integer (SubPriorityBits)) - 1; Temp5 := Subpriority and Temp4; return Temp3 or Temp5; end Encoded_Priority; ------------------ -- Set_Priority -- ------------------ procedure Set_Priority (IRQn : Interrupt_ID; Preempt_Priority : UInt32; Subpriority : UInt32) is Priority_Group : constant UInt32 := Priority_Grouping; begin Set_Priority (IRQn, Encoded_Priority (Priority_Group, Preempt_Priority, Subpriority)); end Set_Priority; ---------------------- -- Enable_Interrupt -- ---------------------- procedure Enable_Interrupt (IRQn : Interrupt_ID) is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); begin NVIC.ISER (Index) := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); end Enable_Interrupt; ----------------------- -- Disable_Interrupt -- ----------------------- procedure Disable_Interrupt (IRQn : Interrupt_ID) is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); begin -- NVIC->ICER[((uint32_t)(IRQn)>>5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); NVIC.ICER (Index) := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); end Disable_Interrupt; ------------ -- Active -- ------------ function Active (IRQn : Interrupt_ID) return Boolean is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); Value : constant UInt32 := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); begin return (NVIC.IABR (Index) and Value) /= 0; end Active; ------------- -- Pending -- ------------- function Pending (IRQn : Interrupt_ID) return Boolean is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); Value : constant UInt32 := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); begin return (NVIC.ISPR (Index) and Value) /= 0; end Pending; ----------------- -- Set_Pending -- ----------------- procedure Set_Pending (IRQn : Interrupt_ID) is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); begin NVIC.ISPR (Index) := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); end Set_Pending; ------------------- -- Clear_Pending -- ------------------- procedure Clear_Pending (IRQn : Interrupt_ID) is IRQn_As_Word : constant UInt32 := UInt32 (IRQn); Index : constant Natural := Integer (Shift_Right (IRQn_As_Word, 5)); begin NVIC.ICPR (Index) := Shift_Left (1, Integer (IRQn_As_Word and 16#1F#)); end Clear_Pending; ------------------ -- Reset_System -- ------------------ procedure Reset_System is Key : constant := 16#05FA#; -- required for write to be accepted use Memory_Barriers; begin -- Ensure all outstanding memory accesses including -- buffered writes are completed Data_Synchronization_Barrier; SCB.AIRCR := Shift_Left (Key, SCB_AIRCR_VECTKEY_Pos) or -- keep priority group unchanged (SCB.AIRCR and SCB_AIRCR_PRIGROUP_Mask) or SCB_AIRCR_SYSRESETREQ_Mask; -- TODO: why is all code from here onward in the CMSIS??? Data_Synchronization_Barrier; -- wait until reset pragma Warnings (Off); <<spin>> goto spin; pragma Warnings (On); end Reset_System; end Cortex_M.NVIC;
Fix indentation
Cortex_M.NVIC: Fix indentation
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
8b2e4222df356de24037efd59249c57161866f50
awa/plugins/awa-votes/src/awa-votes-modules.adb
awa/plugins/awa-votes/src/awa-votes-modules.adb
----------------------------------------------------------------------- -- awa-votes-modules -- Module votes -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.Permissions; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Votes.Beans; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Votes.Models; with ADO.SQL; with ADO.Sessions; with ADO.Sessions.Entities; package body AWA.Votes.Modules is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module"); package Register is new AWA.Modules.Beans (Module => Vote_Module, Module_Access => Vote_Module_Access); -- ------------------------------ -- Initialize the votes module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the votes module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Votes.Beans.Votes_Bean", Handler => AWA.Votes.Beans.Create_Vote_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the votes module. -- ------------------------------ function Get_Vote_Module return Vote_Module_Access is function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME); begin return Get; end Get_Vote_Module; -- ------------------------------ -- Vote for the given element and return the total vote for that element. -- ------------------------------ procedure Vote_For (Model : in Vote_Module; Id : in ADO.Identifier; Entity_Type : in String; Permission : in String; Value : in Integer; Total : out Integer) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; Rating : AWA.Votes.Models.Rating_Ref; Vote : AWA.Votes.Models.Vote_Ref; Query : ADO.SQL.Query; Found : Boolean; Ident : constant String := Entity_Type & ADO.Identifier'Image (Id); begin -- Check that the user has the vote permission on the given object. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Id); Log.Info ("User {0} votes for {1} rating {2}", ADO.Identifier'Image (User.Get_Id), Ident, Integer'Image (Value)); Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); -- Get the vote associated with the object for the user. Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id"); Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type " & "and o.user_id = :user_id"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Query.Bind_Param ("user_id", User.Get_Id); Vote.Find (DB, Query, Found); if not Found then Query.Clear; -- Get the rating associated with the object. Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Rating.Find (DB, Query, Found); -- Create it if it does not exist. if not Found then Log.Info ("Creating rating for {0}", Ident); Rating.Set_For_Entity_Id (Id); Rating.Set_For_Entity_Type (Kind); Rating.Set_Rating (Value); Rating.Set_Vote_Count (1); else Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1); Rating.Set_Rating (Value + Rating.Get_Rating); end if; Rating.Save (DB); Vote.Set_User (User); Vote.Set_Entity (Rating); else Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity); Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating); Rating.Save (DB); end if; Vote.Set_Rating (Value); Vote.Save (DB); -- Return the total rating for the element. Total := Rating.Get_Rating; Ctx.Commit; end Vote_For; end AWA.Votes.Modules;
----------------------------------------------------------------------- -- awa-votes-modules -- Module votes -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Security.Permissions; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Votes.Beans; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Votes.Models; with ADO.SQL; with ADO.Sessions; with ADO.Sessions.Entities; package body AWA.Votes.Modules is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module"); package Register is new AWA.Modules.Beans (Module => Vote_Module, Module_Access => Vote_Module_Access); -- ------------------------------ -- Initialize the votes module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the votes module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Votes.Beans.Votes_Bean", Handler => AWA.Votes.Beans.Create_Vote_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the votes module. -- ------------------------------ function Get_Vote_Module return Vote_Module_Access is function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME); begin return Get; end Get_Vote_Module; -- ------------------------------ -- Vote for the given element and return the total vote for that element. -- ------------------------------ procedure Vote_For (Model : in Vote_Module; Id : in ADO.Identifier; Entity_Type : in String; Permission : in String; Value : in Integer; Total : out Integer) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; Rating : AWA.Votes.Models.Rating_Ref; Vote : AWA.Votes.Models.Vote_Ref; Query : ADO.SQL.Query; Found : Boolean; Ident : constant String := Entity_Type & ADO.Identifier'Image (Id); begin -- Check that the user has the vote permission on the given object. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Id); Log.Info ("User {0} votes for {1} rating {2}", ADO.Identifier'Image (User), Ident, Integer'Image (Value)); Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); -- Get the vote associated with the object for the user. Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id"); Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type " & "and o.user_id = :user_id"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Query.Bind_Param ("user_id", User); Vote.Find (DB, Query, Found); if not Found then Query.Clear; -- Get the rating associated with the object. Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Rating.Find (DB, Query, Found); -- Create it if it does not exist. if not Found then Log.Info ("Creating rating for {0}", Ident); Rating.Set_For_Entity_Id (Id); Rating.Set_For_Entity_Type (Kind); Rating.Set_Rating (Value); Rating.Set_Vote_Count (1); else Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1); Rating.Set_Rating (Value + Rating.Get_Rating); end if; Rating.Save (DB); Vote.Set_User_Id (User); Vote.Set_Entity (Rating); else Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity); Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating); Rating.Save (DB); end if; Vote.Set_Rating (Value); Vote.Save (DB); -- Return the total rating for the element. Total := Rating.Get_Rating; Ctx.Commit; end Vote_For; end AWA.Votes.Modules;
Update for the new model
Update for the new model
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6442c5a42e69f793e3579520f140f5d263a569e8
src/wiki-attributes.ads
src/wiki-attributes.ads
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 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; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- == Attributes == -- The `Attributes` package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the `Attribute_List` -- with some operations to append or query for an attribute. Attributes are used for -- the Wiki document representation to describe the HTML attributes that were parsed and -- several parameters that describe Wiki content (links, ...). -- -- The Wiki filters and Wiki plugins have access to the attributes before they are added -- to the Wiki document. They can check them or modify them according to their needs. -- -- The Wiki renderers use the attributes to render the final HTML content. package Wiki.Attributes is pragma Preelaborate; 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; -- 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 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 String; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString); -- 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;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- == Attributes == -- The `Attributes` package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the `Attribute_List` -- with some operations to append or query for an attribute. Attributes are used for -- the Wiki document representation to describe the HTML attributes that were parsed and -- several parameters that describe Wiki content (links, ...). -- -- The Wiki filters and Wiki plugins have access to the attributes before they are added -- to the Wiki document. They can check them or modify them according to their needs. -- -- The Wiki renderers use the attributes to render the final HTML content. package Wiki.Attributes is pragma Preelaborate; 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; -- 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 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); procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.WString); procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString); procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.BString); -- 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;
Add an Append procedure that accepts a BString builder
Add an Append procedure that accepts a BString builder
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
01462610c0d7dca47d7fc8481bc6f0ea3903c6b5
src/security-contexts.ads
src/security-contexts.ads
----------------------------------------------------------------------- -- 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.Finalization; with Security.Permissions; with Security.Policies; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; Invalid_Policy : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access; pragma Inline_Always (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; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean); -- 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); -- 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); -- 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); -- Set a policy context information represented by <b>Value</b> and associated with -- the <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); -- 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; -- 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; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private type Permission_Cache is record Perm : Security.Permissions.Permission_Type; Result : Boolean; end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Policies.Policy_Manager_Access := null; Principal : Security.Principal_Access := null; Contexts : Security.Policies.Policy_Context_Array_Access := null; end record; end Security.Contexts;
----------------------------------------------------------------------- -- 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.Finalization; with Security.Permissions; with Security.Policies; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; Invalid_Policy : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access; pragma Inline_Always (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; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean); -- 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); -- 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); -- 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); -- Set a policy context information represented by <b>Value</b> and associated with -- the <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); -- 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; -- 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; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private -- type Permission_Cache is record -- Perm : Security.Permissions.Permission_Type; -- Result : Boolean; -- end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Policies.Policy_Manager_Access := null; Principal : Security.Principal_Access := null; Contexts : Security.Policies.Policy_Context_Array_Access := null; end record; end Security.Contexts;
Remove the Permission_Cache record
Remove the Permission_Cache record
Ada
apache-2.0
stcarrez/ada-security
3244ff21b86066e79a9db9b9fbbde0166e7f6aed
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Space (C : in Wide_Wide_Character) return Boolean; function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Space (C : in Wide_Wide_Character) return Boolean is begin return C = ' ' or C = LF or C = CR; end Is_Space; function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; procedure Skip_Spaces (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); if not Is_Space (C) then Put_Back (P, C); return; end if; end loop; end Skip_Spaces; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Name); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Name, P.Attributes); End_Element (P, Name); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Name, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin loop Peek (P, C); exit when C = ';'; if Len < Name'Last then Len := Len + 1; end if; Name (Len) := Ada.Characters.Conversions.To_Character (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Name); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Name, P.Attributes); End_Element (P, Name); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Name, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin loop Peek (P, C); exit when C = ';'; if Len < Name'Last then Len := Len + 1; end if; Name (Len) := Ada.Characters.Conversions.To_Character (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; end Parse_Entity; end Wiki.Parsers.Html;
Use the wiki helpers Skip_Spaces operation
Use the wiki helpers Skip_Spaces operation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2db4d43e1b73ba25dba39af6be5fbba436a052d0
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; -- with Security.Permissions; with Security.Permissions.Tests; with Security.Policies.URLs; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map; begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : constant Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : constant Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based (1000 calls)"); T.Assert (Result, "Permission not granted"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URL : constant String := "/admin/list.html"; P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin T.Assert (Contexts.Has_Permission (Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URL : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URL=" & URL); -- Set the role. User.Roles (Admin) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URL=" & URL); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URL => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; -- with Security.Permissions; with Security.Permissions.Tests; with Security.Policies.URLs; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map; begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : constant Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : constant Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is use Security.Permissions.Tests; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin := R.Find_Role ("admin"); T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was granted but user has no role"); User.Roles (Admin) := True; T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission was not granted and user has admin role"); declare S : Util.Measures.Stamp; Result : Boolean; begin for I in 1 .. 1_000 loop Result := Contexts.Has_Permission (Permission => P_Admin.Permission); end loop; Util.Measures.Report (S, "Has_Permission role based (1000 calls)"); T.Assert (Result, "Permission not granted"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URL : constant String := "/admin/list.html"; P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin T.Assert (Contexts.Has_Permission (Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URL : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); U := Security.Policies.URLs.Get_URL_Policy (M); Admin := R.Find_Role (Role); declare P : constant URLs.URL_Permission (URL'Length) := URLs.URL_Permission '(Len => URL'Length, URL => URL); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context, Permission => P), "Permission was granted for user without role. URL=" & URL); -- Set the role. User.Roles (Admin) := True; T.Assert (U.Has_Permission (Context => Context, Permission => P), "Permission was not granted for user with role. URL=" & URL); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URL => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URL => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URL => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Simplify calls to Has_Permission
Simplify calls to Has_Permission
Ada
apache-2.0
Letractively/ada-security
ac99c7062d423ad4871b0867b5b375493dcb4a10
regtests/ado-testsuite.adb
regtests/ado-testsuite.adb
----------------------------------------------------------------------- -- ado-testsuite -- Testsuite for ADO -- 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 ADO.Tests; with ADO.Sequences.Tests; with ADO.Schemas.Tests; with ADO.Objects.Tests; with ADO.Queries.Tests; with ADO.Parameters.Tests; package body ADO.Testsuite is use ADO.Tests; procedure Drivers (Suite : in Util.Tests.Access_Test_Suite); procedure Drivers (Suite : in Util.Tests.Access_Test_Suite) is separate; 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 ADO.Parameters.Tests.Add_Tests (Ret); ADO.Sequences.Tests.Add_Tests (Ret); ADO.Objects.Tests.Add_Tests (Ret); ADO.Tests.Add_Tests (Ret); ADO.Schemas.Tests.Add_Tests (Ret); Drivers (Ret); ADO.Queries.Tests.Add_Tests (Ret); return Ret; end Suite; end ADO.Testsuite;
----------------------------------------------------------------------- -- ado-testsuite -- Testsuite for ADO -- 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 ADO.Tests; with ADO.Sequences.Tests; with ADO.Schemas.Tests; with ADO.Objects.Tests; with ADO.Queries.Tests; with ADO.Parameters.Tests; with ADO.Datasets.Tests; package body ADO.Testsuite is use ADO.Tests; procedure Drivers (Suite : in Util.Tests.Access_Test_Suite); procedure Drivers (Suite : in Util.Tests.Access_Test_Suite) is separate; 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 ADO.Parameters.Tests.Add_Tests (Ret); ADO.Sequences.Tests.Add_Tests (Ret); ADO.Objects.Tests.Add_Tests (Ret); ADO.Tests.Add_Tests (Ret); ADO.Schemas.Tests.Add_Tests (Ret); Drivers (Ret); ADO.Queries.Tests.Add_Tests (Ret); ADO.Datasets.Tests.Add_Tests (Ret); return Ret; end Suite; end ADO.Testsuite;
Add the new unit tests
Add the new unit tests
Ada
apache-2.0
stcarrez/ada-ado
d52a1b02cb221c730d822b1315dc7d58bc95f897
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017, 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 AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Storages.Models; with ADO.Objects; with ADO.Sessions; with ADO.Statements; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX); begin Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix)); end Configure; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Get the image prefix that was configured for the Blog module. -- ------------------------------ function Get_Image_Prefix (Module : in Blog_Module) return Wiki.Strings.UString is begin return Module.Image_Prefix; end Get_Image_Prefix; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Workspaces.Modules.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id, List => (ACL_Delete_Blog.Permission, ACL_Update_Post.Permission, ACL_Create_Post.Permission, ACL_Delete_Post.Permission)); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Publish_Date : in ADO.Nullable_Time; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if not Publish_Date.Is_Null then Post.Set_Publish_Date (Publish_Date); end if; if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; -- ------------------------------ -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. -- ------------------------------ procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref) is pragma Unreferenced (Model); use type AWA.Storages.Models.Storage_Type; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement; Kind : AWA.Storages.Models.Storage_Type; begin if Width = Natural'Last or Height = Natural'Last then Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); elsif Width > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data); Query.Bind_Param ("width", Width); elsif Height > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data); Query.Bind_Param ("height", Height); else Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); end if; Query.Bind_Param ("post_id", Post_Id); Query.Bind_Param ("store_id", Image_Id); Query.Bind_Param ("user_id", User); Query.Execute; if not Query.Has_Elements then Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id)); raise ADO.Objects.NOT_FOUND; end if; Mime := Query.Get_Unbounded_String (0); Date := Query.Get_Time (1); Width := Query.Get_Natural (4); Height := Query.Get_Natural (5); Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3)); if Kind = AWA.Storages.Models.DATABASE then Into := Query.Get_Blob (6); else null; end if; end Load_Image; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017, 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 AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Storages.Models; with ADO.Objects; with ADO.Sessions; with ADO.Statements; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX); begin Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix)); end Configure; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Get the image prefix that was configured for the Blog module. -- ------------------------------ function Get_Image_Prefix (Module : in Blog_Module) return Wiki.Strings.UString is begin return Module.Image_Prefix; end Get_Image_Prefix; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Workspaces.Modules.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id, List => (ACL_Delete_Blog.Permission, ACL_Update_Post.Permission, ACL_Create_Post.Permission, ACL_Delete_Post.Permission)); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); if Status = AWA.Blogs.Models.POST_PUBLISHED then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Publish_Date : in ADO.Nullable_Time; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if not Publish_Date.Is_Null then Post.Set_Publish_Date (Publish_Date); end if; if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; -- ------------------------------ -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. -- ------------------------------ procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref) is pragma Unreferenced (Model); use type AWA.Storages.Models.Storage_Type; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement; Kind : AWA.Storages.Models.Storage_Type; begin if Width = Natural'Last or Height = Natural'Last then Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); elsif Width > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data); Query.Bind_Param ("width", Width); elsif Height > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data); Query.Bind_Param ("height", Height); else Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); end if; Query.Bind_Param ("post_id", Post_Id); Query.Bind_Param ("store_id", Image_Id); Query.Bind_Param ("user_id", User); Query.Execute; if not Query.Has_Elements then Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id)); raise ADO.Objects.NOT_FOUND; end if; Mime := Query.Get_Unbounded_String (0); Date := Query.Get_Time (1); Width := Query.Get_Natural (4); Height := Query.Get_Natural (5); Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3)); if Kind = AWA.Storages.Models.DATABASE then Into := Query.Get_Blob (6); else null; end if; end Load_Image; end AWA.Blogs.Modules;
Fix Create_Post to also setup the post publication date when the post is created in the PUBLISHED state
Fix Create_Post to also setup the post publication date when the post is created in the PUBLISHED state
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
bcb122285c8fd1094ebed5bd8c38c4fc43c17727
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with ADO.Sessions; with Ada.Calendar; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with ADO.Objects; with ADO.Sessions; with Ada.Calendar; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Workspaces.Modules.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id, List => (ACL_Delete_Blog.Permission, ACL_Update_Post.Permission, ACL_Create_Post.Permission, ACL_Delete_Post.Permission)); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Modules;
Change the blog permission creation to make a create/update/delete permission
Change the blog permission creation to make a create/update/delete permission
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5d66700eff241ffbae431fab4470d48090f6d999
awa/plugins/awa-votes/src/awa-votes-modules.ads
awa/plugins/awa-votes/src/awa-votes-modules.ads
----------------------------------------------------------------------- -- awa-votes-modules -- Module votes -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; package AWA.Votes.Modules is -- The name under which the module is registered. NAME : constant String := "votes"; -- ------------------------------ -- Module votes -- ------------------------------ type Vote_Module is new AWA.Modules.Module with private; type Vote_Module_Access is access all Vote_Module'Class; -- Initialize the votes module. overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the votes module. function Get_Vote_Module return Vote_Module_Access; -- Vote for the given element. procedure Vote_For (Model : in Vote_Module; Id : in ADO.Identifier; Entity_Type : in String; Permission : in String; Rating : in Integer); private type Vote_Module is new AWA.Modules.Module with null record; end AWA.Votes.Modules;
----------------------------------------------------------------------- -- awa-votes-modules -- Module votes -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; package AWA.Votes.Modules is -- The name under which the module is registered. NAME : constant String := "votes"; -- ------------------------------ -- Module votes -- ------------------------------ type Vote_Module is new AWA.Modules.Module with private; type Vote_Module_Access is access all Vote_Module'Class; -- Initialize the votes module. overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the votes module. function Get_Vote_Module return Vote_Module_Access; -- Vote for the given element and return the total vote for that element. procedure Vote_For (Model : in Vote_Module; Id : in ADO.Identifier; Entity_Type : in String; Permission : in String; Value : in Integer; Total : out Integer); private type Vote_Module is new AWA.Modules.Module with null record; end AWA.Votes.Modules;
Return the total vote after the vote is updated
Return the total vote after the vote is updated
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
fa07f3b643e77f21269d4e14a47f86fa8ad2c1f1
samples/beans/facebook.adb
samples/beans/facebook.adb
----------------------------------------------------------------------- -- facebook - Use Facebook Graph API -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Http.Clients; with Util.Http.Rest; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.Mappers.Vector_Mapper; with ASF.Sessions; with ASF.Contexts.Faces; with ASF.Events.Faces.Actions; package body Facebook is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Facebook"); type Friend_Field_Type is (FIELD_NAME, FIELD_ID); type Feed_Field_Type is (FIELD_ID, FIELD_NAME, FIELD_FROM, FIELD_MESSAGE, FIELD_PICTURE, FIELD_LINK, FIELD_DESCRIPTION, FIELD_ICON); procedure Set_Member (Into : in out Friend_Info; Field : in Friend_Field_Type; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Feed_Info; Field : in Feed_Field_Type; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Friend_Info; Field : in Friend_Field_Type; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => Into.Id := Value; when FIELD_NAME => Into.Name := Value; end case; end Set_Member; procedure Set_Member (Into : in out Feed_Info; Field : in Feed_Field_Type; Value : in Util.Beans.Objects.Object) is begin Log.Info ("Set field {0} to {1}", Feed_Field_Type'Image (Field), Util.Beans.Objects.To_String (Value)); case Field is when FIELD_ID => Into.Id := Value; when FIELD_NAME => Into.Name := Value; when FIELD_FROM => Into.From := Value; when FIELD_MESSAGE => Into.Message := Value; when FIELD_LINK => Into.Link := Value; when FIELD_PICTURE => Into.Picture := Value; when FIELD_ICON => Into.Icon := Value; when FIELD_DESCRIPTION => Into.Description := Value; end case; end Set_Member; package Friend_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Friend_Info, Element_Type_Access => Friend_Info_Access, Fields => Friend_Field_Type, Set_Member => Set_Member); package Friend_Vector_Mapper is new Util.Serialize.Mappers.Vector_Mapper (Vectors => Friend_List.Vectors, Element_Mapper => Friend_Mapper); package Feed_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Feed_Info, Element_Type_Access => Feed_Info_Access, Fields => Feed_Field_Type, Set_Member => Set_Member); package Feed_Vector_Mapper is new Util.Serialize.Mappers.Vector_Mapper (Vectors => Feed_List.Vectors, Element_Mapper => Feed_Mapper); Friend_Map : aliased Friend_Mapper.Mapper; Friend_Vector_Map : aliased Friend_Vector_Mapper.Mapper; Feed_Map : aliased Feed_Mapper.Mapper; Feed_Vector_Map : aliased Feed_Vector_Mapper.Mapper; procedure Get_Friends is new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Friend_Vector_Mapper); procedure Get_Feeds is new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Feed_Vector_Mapper); -- ------------------------------ -- Get the access token from the user session. -- ------------------------------ function Get_Access_Token return String is use type ASF.Contexts.Faces.Faces_Context_Access; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return ""; end if; declare S : ASF.Sessions.Session := Context.Get_Session; begin if not S.Is_Valid then return ""; end if; declare Token : Util.Beans.Objects.Object := S.Get_Attribute ("access_token"); begin if Util.Beans.Objects.Is_Null (Token) then return ""; else return Util.Beans.Objects.To_String (Token); end if; end; end; end Get_Access_Token; -- ------------------------------ -- 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 Friend_Info; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return From.Name; elsif Name = "id" then return From.Id; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Feed_Info; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return From.Id; elsif Name = "name" then return From.Name; elsif Name = "from" then return From.From; elsif Name = "message" then return From.Message; elsif Name = "picture" then return From.Picture; elsif Name = "link" then return From.Link; elsif Name = "description" then return From.Description; elsif Name = "icon" then return From.Icon; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Friend_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "hasAccessToken" then return Util.Beans.Objects.To_Object (False); end if; return Friend_List.List_Bean (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Create a Friend_List bean instance. -- ------------------------------ function Create_Friends_Bean return Util.Beans.Basic.Readonly_Bean_Access is List : Friend_List_Bean_Access := new Friend_List_Bean; Token : constant String := Get_Access_Token; begin if Token'Length > 0 then declare C : Util.Http.Rest.Client; begin Log.Info ("Getting the Facebook friends"); Get_Friends ("https://graph.facebook.com/me/friends?access_token=" & Token, Friend_Vector_Map'Access, "/data", List.List'Access); end; end if; return List.all'Access; end Create_Friends_Bean; -- ------------------------------ -- Build and return a Facebook feed list. -- ------------------------------ function Create_Feed_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is List : Feed_List.List_Bean_Access := new Feed_List.List_Bean; Token : constant String := Get_Access_Token; begin if Token'Length > 0 then declare C : Util.Http.Rest.Client; begin Log.Info ("Getting the Facebook feeds"); Get_Feeds ("https://graph.facebook.com/me/home?access_token=" & Token, Feed_Vector_Map'Access, "/data", List.List'Access); end; end if; return List.all'Access; end Create_Feed_List_Bean; -- ------------------------------ -- Get the user information identified by the given name. -- ------------------------------ overriding function Get_Value (From : in Facebook_Auth; Name : in String) return Util.Beans.Objects.Object is use type ASF.Contexts.Faces.Faces_Context_Access; F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if F /= null and Name = "authenticate_url" then declare S : ASF.Sessions.Session := F.Get_Session (True); Id : constant String := S.Get_Id; State : constant String := From.Get_State (Id); Params : constant String := From.Get_Auth_Params (State, "read_stream"); begin Log.Info ("OAuth params: {0}", Params); return Util.Beans.Objects.To_Object ("https://www.facebook.com/dialog/oauth?" & Params); end; elsif F /= null and Name = "isAuthenticated" then declare S : ASF.Sessions.Session := F.Get_Session (False); begin if S.Is_Valid and then not Util.Beans.Objects.Is_Null (S.Get_Attribute ("access_token")) then return Util.Beans.Objects.To_Object (True); else return Util.Beans.Objects.To_Object (False); end if; end; end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Authenticate result from Facebook. -- ------------------------------ procedure Authenticate (From : in out Facebook_Auth; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type Security.OAuth.Clients.Access_Token_Access; F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := F.Get_Session; State : constant String := F.Get_Parameter (Security.OAuth.State); Code : constant String := F.Get_Parameter (Security.OAuth.Code); begin Log.Info ("Auth code {0} for state {1}", Code, State); if Session.Is_Valid then if From.Is_Valid_State (Session.Get_Id, State) then declare Acc : Security.OAuth.Clients.Access_Token_Access := From.Request_Access_Token (Code); begin if Acc /= null then Log.Info ("Access token is {0}", Acc.Get_Name); Session.Set_Attribute ("access_token", Util.Beans.Objects.To_Object (Acc.Get_Name)); end if; end; end if; end if; end Authenticate; package Authenticate_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Facebook_Auth, Method => Authenticate, Name => "authenticate"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Authenticate_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Facebook_Auth) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; begin Friend_Map.Add_Default_Mapping; Friend_Vector_Map.Set_Mapping (Friend_Map'Access); Feed_Map.Add_Mapping ("id", FIELD_ID); Feed_Map.Add_Mapping ("name", FIELD_NAME); Feed_Map.Add_Mapping ("message", FIELD_MESSAGE); Feed_Map.Add_Mapping ("description", FIELD_DESCRIPTION); Feed_Map.Add_Mapping ("from/name", FIELD_FROM); Feed_Map.Add_Mapping ("picture", FIELD_PICTURE); Feed_Map.Add_Mapping ("link", FIELD_LINK); Feed_Map.Add_Mapping ("icon", FIELD_ICON); Feed_Vector_Map.Set_Mapping (Feed_Map'Access); end Facebook;
----------------------------------------------------------------------- -- facebook - Use Facebook Graph API -- 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 Util.Log.Loggers; with Util.Http.Rest; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.Mappers.Vector_Mapper; with ASF.Sessions; with ASF.Contexts.Faces; with ASF.Events.Faces.Actions; package body Facebook is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Facebook"); type Friend_Field_Type is (FIELD_NAME, FIELD_ID); type Feed_Field_Type is (FIELD_ID, FIELD_NAME, FIELD_FROM, FIELD_MESSAGE, FIELD_PICTURE, FIELD_LINK, FIELD_DESCRIPTION, FIELD_ICON); procedure Set_Member (Into : in out Friend_Info; Field : in Friend_Field_Type; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Feed_Info; Field : in Feed_Field_Type; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Friend_Info; Field : in Friend_Field_Type; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => Into.Id := Value; when FIELD_NAME => Into.Name := Value; end case; end Set_Member; procedure Set_Member (Into : in out Feed_Info; Field : in Feed_Field_Type; Value : in Util.Beans.Objects.Object) is begin Log.Info ("Set field {0} to {1}", Feed_Field_Type'Image (Field), Util.Beans.Objects.To_String (Value)); case Field is when FIELD_ID => Into.Id := Value; when FIELD_NAME => Into.Name := Value; when FIELD_FROM => Into.From := Value; when FIELD_MESSAGE => Into.Message := Value; when FIELD_LINK => Into.Link := Value; when FIELD_PICTURE => Into.Picture := Value; when FIELD_ICON => Into.Icon := Value; when FIELD_DESCRIPTION => Into.Description := Value; end case; end Set_Member; package Friend_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Friend_Info, Element_Type_Access => Friend_Info_Access, Fields => Friend_Field_Type, Set_Member => Set_Member); package Friend_Vector_Mapper is new Util.Serialize.Mappers.Vector_Mapper (Vectors => Friend_List.Vectors, Element_Mapper => Friend_Mapper); package Feed_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Feed_Info, Element_Type_Access => Feed_Info_Access, Fields => Feed_Field_Type, Set_Member => Set_Member); package Feed_Vector_Mapper is new Util.Serialize.Mappers.Vector_Mapper (Vectors => Feed_List.Vectors, Element_Mapper => Feed_Mapper); Friend_Map : aliased Friend_Mapper.Mapper; Friend_Vector_Map : aliased Friend_Vector_Mapper.Mapper; Feed_Map : aliased Feed_Mapper.Mapper; Feed_Vector_Map : aliased Feed_Vector_Mapper.Mapper; procedure Get_Friends is new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Friend_Vector_Mapper); procedure Get_Feeds is new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Feed_Vector_Mapper); -- ------------------------------ -- Get the access token from the user session. -- ------------------------------ function Get_Access_Token return String is use type ASF.Contexts.Faces.Faces_Context_Access; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return ""; end if; declare S : constant ASF.Sessions.Session := Context.Get_Session; begin if not S.Is_Valid then return ""; end if; declare Token : constant Util.Beans.Objects.Object := S.Get_Attribute ("access_token"); begin if Util.Beans.Objects.Is_Null (Token) then return ""; else return Util.Beans.Objects.To_String (Token); end if; end; end; end Get_Access_Token; -- ------------------------------ -- 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 Friend_Info; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return From.Name; elsif Name = "id" then return From.Id; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Feed_Info; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return From.Id; elsif Name = "name" then return From.Name; elsif Name = "from" then return From.From; elsif Name = "message" then return From.Message; elsif Name = "picture" then return From.Picture; elsif Name = "link" then return From.Link; elsif Name = "description" then return From.Description; elsif Name = "icon" then return From.Icon; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Friend_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "hasAccessToken" then return Util.Beans.Objects.To_Object (False); end if; return Friend_List.List_Bean (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Create a Friend_List bean instance. -- ------------------------------ function Create_Friends_Bean return Util.Beans.Basic.Readonly_Bean_Access is List : Friend_List_Bean_Access := new Friend_List_Bean; Token : constant String := Get_Access_Token; begin if Token'Length > 0 then Log.Info ("Getting the Facebook friends"); Get_Friends ("https://graph.facebook.com/me/friends?access_token=" & Token, Friend_Vector_Map'Access, "/data", List.List'Access); end if; return List.all'Access; end Create_Friends_Bean; -- ------------------------------ -- Build and return a Facebook feed list. -- ------------------------------ function Create_Feed_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is List : Feed_List.List_Bean_Access := new Feed_List.List_Bean; Token : constant String := Get_Access_Token; begin if Token'Length > 0 then Log.Info ("Getting the Facebook feeds"); Get_Feeds ("https://graph.facebook.com/me/home?access_token=" & Token, Feed_Vector_Map'Access, "/data", List.List'Access); end if; return List.all'Access; end Create_Feed_List_Bean; -- ------------------------------ -- Get the user information identified by the given name. -- ------------------------------ overriding function Get_Value (From : in Facebook_Auth; Name : in String) return Util.Beans.Objects.Object is use type ASF.Contexts.Faces.Faces_Context_Access; F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if F /= null and Name = "authenticate_url" then declare S : constant ASF.Sessions.Session := F.Get_Session (True); Id : constant String := S.Get_Id; State : constant String := From.Get_State (Id); Params : constant String := From.Get_Auth_Params (State, "read_stream"); begin Log.Info ("OAuth params: {0}", Params); return Util.Beans.Objects.To_Object ("https://www.facebook.com/dialog/oauth?" & Params); end; elsif F /= null and Name = "isAuthenticated" then declare S : constant ASF.Sessions.Session := F.Get_Session (False); begin if S.Is_Valid and then not Util.Beans.Objects.Is_Null (S.Get_Attribute ("access_token")) then return Util.Beans.Objects.To_Object (True); else return Util.Beans.Objects.To_Object (False); end if; end; end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Authenticate result from Facebook. -- ------------------------------ procedure Authenticate (From : in out Facebook_Auth; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); use type Security.OAuth.Clients.Access_Token_Access; F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := F.Get_Session; State : constant String := F.Get_Parameter (Security.OAuth.State); Code : constant String := F.Get_Parameter (Security.OAuth.Code); begin Log.Info ("Auth code {0} for state {1}", Code, State); if Session.Is_Valid then if From.Is_Valid_State (Session.Get_Id, State) then declare Acc : constant Security.OAuth.Clients.Access_Token_Access := From.Request_Access_Token (Code); begin if Acc /= null then Log.Info ("Access token is {0}", Acc.Get_Name); Session.Set_Attribute ("access_token", Util.Beans.Objects.To_Object (Acc.Get_Name)); end if; end; end if; end if; end Authenticate; package Authenticate_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Facebook_Auth, Method => Authenticate, Name => "authenticate"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Authenticate_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Facebook_Auth) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; begin Friend_Map.Add_Default_Mapping; Friend_Vector_Map.Set_Mapping (Friend_Map'Access); Feed_Map.Add_Mapping ("id", FIELD_ID); Feed_Map.Add_Mapping ("name", FIELD_NAME); Feed_Map.Add_Mapping ("message", FIELD_MESSAGE); Feed_Map.Add_Mapping ("description", FIELD_DESCRIPTION); Feed_Map.Add_Mapping ("from/name", FIELD_FROM); Feed_Map.Add_Mapping ("picture", FIELD_PICTURE); Feed_Map.Add_Mapping ("link", FIELD_LINK); Feed_Map.Add_Mapping ("icon", FIELD_ICON); Feed_Vector_Map.Set_Mapping (Feed_Map'Access); end Facebook;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
eb104f2780416e9a8748f4ca009a22f0816c1c3c
src/asf-views-nodes-jsf.ads
src/asf-views-nodes-jsf.ads
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- 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.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Validators; -- The <b>ASF.Views.Nodes.Jsf</b> package implements various JSF Core Tag -- components which alter the component tree but don't need to create -- new UI components in the usual way. The following components are supported: -- -- <f:attribute name='...' value='...'/> -- <f:converter converterId='...'/> -- <f:validateXXX .../> -- <f:facet name='...'>...</f:facet> -- -- The <b>f:attribute</b>, <b>f:converter</b> and <b>f:validateXXX</b> tags don't create any -- component. The <b>f:facet</b> creates components that are inserted as a facet component -- in the component tree. package ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- The <b>Converter_Tag_Node</b> is created in the facelet tree when -- the <f:converter> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Converter_Tag_Node is new Views.Nodes.Tag_Node with private; type Converter_Tag_Node_Access is access all Converter_Tag_Node'Class; -- Create the Converter Tag function Create_Converter_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Convert Date Time Tag -- ------------------------------ -- The <b>Convert_Date_Time_Tag_Node</b> is created in the facelet tree when -- the <f:converterDateTime> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Convert_Date_Time_Tag_Node is new Views.Nodes.Tag_Node with private; type Convert_Date_Time_Tag_Node_Access is access all Convert_Date_Time_Tag_Node'Class; -- Create the Converter Tag function Create_Convert_Date_Time_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Convert_Date_Time_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Validator Tag -- ------------------------------ -- The <b>Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateXXX> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Validator_Tag_Node is new Views.Nodes.Tag_Node with private; type Validator_Tag_Node_Access is access all Validator_Tag_Node'Class; -- Create the Validator Tag function Create_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- The <b>Range_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLongRange> element is found. -- The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Range_Validator_Tag_Node is new Validator_Tag_Node with private; type Range_Validator_Tag_Node_Access is access all Range_Validator_Tag_Node'Class; -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- The <b>Length_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLength> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Length_Validator_Tag_Node is new Validator_Tag_Node with private; type Length_Validator_Tag_Node_Access is access all Length_Validator_Tag_Node'Class; -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. function Create_Length_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Attribute Tag -- ------------------------------ -- The <b>Attribute_Tag_Node</b> is created in the facelet tree when -- the <f:attribute> element is found. When building the component tree, -- an attribute is added to the parent component. type Attribute_Tag_Node is new Views.Nodes.Tag_Node with private; type Attribute_Tag_Node_Access is access all Attribute_Tag_Node'Class; -- Create the Attribute Tag function Create_Attribute_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Facet Tag -- ------------------------------ -- The <b>Facet_Tag_Node</b> is created in the facelet tree when -- the <f:facet> element is found. After building the component tree, -- we have to add the component as a facet element of the parent component. -- type Facet_Tag_Node is new Views.Nodes.Tag_Node with private; type Facet_Tag_Node_Access is access all Facet_Tag_Node'Class; -- Create the Facet Tag function Create_Facet_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Metadata Tag -- ------------------------------ -- The <b>Metadata_Tag_Node</b> is created in the facelet tree when -- the <f:metadata> element is found. This special component is inserted as a special -- facet component on the UIView parent component. type Metadata_Tag_Node is new Views.Nodes.Tag_Node with private; type Metadata_Tag_Node_Access is access all Metadata_Tag_Node'Class; -- Create the Metadata Tag function Create_Metadata_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- The elaboration check is disabled on the Create_XXX operation because they -- are referenced by the Components.Core.Factory to define a static UI binding. -- This reference triggers the implicit Elaborate_All for the Nodes.JSF package. -- At the end, we obtain a circular dependency that cannot be resolved. -- It is safe to suppress the elaboration check because these Create_XXX operation -- are not invoked before the application is initialized and a view is rendered. pragma Suppress (Elaboration_Check, On => Create_Attribute_Tag_Node); pragma Suppress (Elaboration_Check, On => Create_Converter_Tag_Node); pragma Suppress (Elaboration_Check, On => Create_Convert_Date_Time_Tag_Node); pragma Suppress (Elaboration_Check, On => Create_Facet_Tag_Node); pragma Suppress (Elaboration_Check, On => Create_Metadata_Tag_Node); pragma Suppress (Elaboration_Check, On => Create_Length_Validator_Tag_Node); pragma Suppress (Elaboration_Check, On => Create_Range_Validator_Tag_Node); pragma Suppress (Elaboration_Check, On => Create_Validator_Tag_Node); private type Converter_Tag_Node is new Views.Nodes.Tag_Node with record Converter : EL.Objects.Object; end record; type Convert_Date_Time_Tag_Node is new Views.Nodes.Tag_Node with record Date_Style : Tag_Attribute_Access; Time_Style : Tag_Attribute_Access; Locale : Tag_Attribute_Access; Pattern : Tag_Attribute_Access; Format : Tag_Attribute_Access; end record; type Validator_Tag_Node is new Views.Nodes.Tag_Node with record Validator : EL.Objects.Object; end record; type Length_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Range_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Attribute_Tag_Node is new Views.Nodes.Tag_Node with record Attr : aliased Tag_Attribute; Attr_Name : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Facet_Tag_Node is new Views.Nodes.Tag_Node with record Facet_Name : Tag_Attribute_Access; end record; type Metadata_Tag_Node is new Views.Nodes.Tag_Node with null record; end ASF.Views.Nodes.Jsf;
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- Copyright (C) 2010, 2011, 2012, 2013, 2014, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Contexts.Facelets; with ASF.Validators; -- The <b>ASF.Views.Nodes.Jsf</b> package implements various JSF Core Tag -- components which alter the component tree but don't need to create -- new UI components in the usual way. The following components are supported: -- -- <f:attribute name='...' value='...'/> -- <f:converter converterId='...'/> -- <f:validateXXX .../> -- <f:facet name='...'>...</f:facet> -- -- The <b>f:attribute</b>, <b>f:converter</b> and <b>f:validateXXX</b> tags don't create any -- component. The <b>f:facet</b> creates components that are inserted as a facet component -- in the component tree. package ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- The <b>Converter_Tag_Node</b> is created in the facelet tree when -- the <f:converter> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Converter_Tag_Node is new Views.Nodes.Tag_Node with private; type Converter_Tag_Node_Access is access all Converter_Tag_Node'Class; -- Create the Converter Tag function Create_Converter_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Convert Date Time Tag -- ------------------------------ -- The <b>Convert_Date_Time_Tag_Node</b> is created in the facelet tree when -- the <f:converterDateTime> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Convert_Date_Time_Tag_Node is new Views.Nodes.Tag_Node with private; type Convert_Date_Time_Tag_Node_Access is access all Convert_Date_Time_Tag_Node'Class; -- Create the Converter Tag function Create_Convert_Date_Time_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Convert_Date_Time_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Validator Tag -- ------------------------------ -- The <b>Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateXXX> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Validator_Tag_Node is new Views.Nodes.Tag_Node with private; type Validator_Tag_Node_Access is access all Validator_Tag_Node'Class; -- Create the Validator Tag function Create_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- The <b>Range_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLongRange> element is found. -- The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Range_Validator_Tag_Node is new Validator_Tag_Node with private; type Range_Validator_Tag_Node_Access is access all Range_Validator_Tag_Node'Class; -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- The <b>Length_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLength> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Length_Validator_Tag_Node is new Validator_Tag_Node with private; type Length_Validator_Tag_Node_Access is access all Length_Validator_Tag_Node'Class; -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. function Create_Length_Validator_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Attribute Tag -- ------------------------------ -- The <b>Attribute_Tag_Node</b> is created in the facelet tree when -- the <f:attribute> element is found. When building the component tree, -- an attribute is added to the parent component. type Attribute_Tag_Node is new Views.Nodes.Tag_Node with private; type Attribute_Tag_Node_Access is access all Attribute_Tag_Node'Class; -- Create the Attribute Tag function Create_Attribute_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Facet Tag -- ------------------------------ -- The <b>Facet_Tag_Node</b> is created in the facelet tree when -- the <f:facet> element is found. After building the component tree, -- we have to add the component as a facet element of the parent component. -- type Facet_Tag_Node is new Views.Nodes.Tag_Node with private; type Facet_Tag_Node_Access is access all Facet_Tag_Node'Class; -- Create the Facet Tag function Create_Facet_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Metadata Tag -- ------------------------------ -- The <b>Metadata_Tag_Node</b> is created in the facelet tree when -- the <f:metadata> element is found. This special component is inserted as a special -- facet component on the UIView parent component. type Metadata_Tag_Node is new Views.Nodes.Tag_Node with private; type Metadata_Tag_Node_Access is access all Metadata_Tag_Node'Class; -- Create the Metadata Tag function Create_Metadata_Tag_Node (Binding : in Binding_Type; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); private type Converter_Tag_Node is new Views.Nodes.Tag_Node with record Converter : EL.Objects.Object; end record; type Convert_Date_Time_Tag_Node is new Views.Nodes.Tag_Node with record Date_Style : Tag_Attribute_Access; Time_Style : Tag_Attribute_Access; Locale : Tag_Attribute_Access; Pattern : Tag_Attribute_Access; Format : Tag_Attribute_Access; end record; type Validator_Tag_Node is new Views.Nodes.Tag_Node with record Validator : EL.Objects.Object; end record; type Length_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Range_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Attribute_Tag_Node is new Views.Nodes.Tag_Node with record Attr : aliased Tag_Attribute; Attr_Name : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Facet_Tag_Node is new Views.Nodes.Tag_Node with record Facet_Name : Tag_Attribute_Access; end record; type Metadata_Tag_Node is new Views.Nodes.Tag_Node with null record; end ASF.Views.Nodes.Jsf;
Use Binding_Type instead of Binding_Access
Use Binding_Type instead of Binding_Access
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d2b46a8a2f88af8deaad0232357987f633127913
mat/src/mat-formats.ads
mat/src/mat-formats.ads
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; package MAT.Formats is -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; package MAT.Formats is -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; end MAT.Formats;
Declare the Size function
Declare the Size function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
20615e50d6093e28fecf5349727ae5276b29bc3a
awa/plugins/awa-setup/src/awa-setup-applications.adb
awa/plugins/awa-setup/src/awa-setup-applications.adb
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Strings; with ASF.Events.Faces.Actions; with ASF.Applications.Main.Configs; with AWA.Applications; package body AWA.Setup.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications"); package Save_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Save, Name => "save"); package Finish_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Finish, Name => "finish"); package Configure_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Configure_Database, Name => "configure_database"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Finish_Binding.Proxy'Access, Configure_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object is begin if Name = "database_name" then return Util.Beans.Objects.To_Object (From.Database.Get_Database); elsif Name = "database_server" then return Util.Beans.Objects.To_Object (From.Database.Get_Server); elsif Name = "database_port" then return Util.Beans.Objects.To_Object (From.Database.Get_Port); elsif Name = "database_user" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user")); elsif Name = "database_password" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password")); end if; if From.Changed.Exists (Name) then return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name))); end if; declare Param : constant String := From.Config.Get (Name); begin return Util.Beans.Objects.To_Object (Param); end; exception when others => return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "database_name" then From.Database.Set_Database (Util.Beans.Objects.To_String (Value)); elsif Name = "database_server" then From.Database.Set_Server (Util.Beans.Objects.To_String (Value)); elsif Name = "database_port" then From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value)); elsif Name = "database_user" then From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value)); elsif Name = "database_password" then From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value)); elsif Name = "callback_url" then From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); From.Changed.Set ("facebook.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); From.Changed.Set ("google-plus.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); else From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Get the database connection string to be used by the application. -- ------------------------------ function Get_Database_URL (From : in Application) return String is use Ada.Strings.Unbounded; Result : Ada.Strings.Unbounded.Unbounded_String; begin Append (Result, "mysql://"); Append (Result, From.Database.Get_Server); if From.Database.Get_Port /= 0 then Append (Result, ":"); Append (Result, Util.Strings.Image (From.Database.Get_Port)); end if; Append (Result, "/"); Append (Result, From.Database.Get_Database); if From.Database.Get_Property ("user") /= "" then Append (Result, "?user="); Append (Result, From.Database.Get_Property ("user")); if From.Database.Get_Property ("password") /= "" then Append (Result, "&password="); Append (Result, From.Database.Get_Property ("password")); end if; end if; return To_String (Result); end Get_Database_URL; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Configure database"); end Configure_Database; -- ------------------------------ -- Save the configuration. -- ------------------------------ procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Path : constant String := Ada.Strings.Unbounded.To_String (From.Path); New_File : constant String := Path & ".tmp"; Output : Ada.Text_IO.File_Type; procedure Read_Property (Line : in String) is Pos : constant Natural := Util.Strings.Index (Line, '='); begin if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then Ada.Text_IO.Put_Line (Output, Line); return; end if; Ada.Text_IO.Put (Output, Line (Line'First .. Pos)); Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1))); end Read_Property; begin Log.Info ("Saving configuration file {0}", Path); From.Changed.Set ("database", From.Get_Database_URL); Ada.Text_IO.Create (File => Output, Name => New_File); Util.Files.Read_File (Path, Read_Property'Access); Ada.Text_IO.Close (Output); Ada.Directories.Delete_File (Path); Ada.Directories.Rename (Old_Name => New_File, New_Name => Path); end Save; -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Finish configuration"); From.Done := True; end Finish; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Enter in the application setup -- ------------------------------ procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class) is begin Log.Info ("Entering configuration for {0}", Config); App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config); begin App.Config.Load_Properties (Config); Util.Log.Loggers.Initialize (Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file: {0}", Config); end; App.Initialize (App.Config, App.Factory); App.Set_Global ("contextPath", App.Config.Get ("contextPath")); App.Set_Global ("setup", Util.Beans.Objects.To_Object (App'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Mapping (Pattern => "*.html", Name => "faces"); App.Add_Mapping (Pattern => "*.css", Name => "files"); App.Add_Mapping (Pattern => "*.js", Name => "files"); declare Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P); Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths); begin ASF.Applications.Main.Configs.Read_Configuration (App, Path); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Setup configuration file '{0}' does not exist", Path); end; declare URL : constant String := App.Config.Get ("google-plus.callback_url", ""); Pos : Natural := Util.Strings.Index (URL, '#'); begin if Pos > 0 then App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1)); end if; end; App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db")); Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access); while not App.Done loop delay 5.0; end loop; Server.Remove_Application (App'Unchecked_Access); end Setup; end AWA.Setup.Applications;
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Strings; with ASF.Events.Faces.Actions; with ASF.Applications.Main.Configs; with AWA.Applications; package body AWA.Setup.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications"); package Save_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Save, Name => "save"); package Finish_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Finish, Name => "finish"); package Configure_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Configure_Database, Name => "configure_database"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Finish_Binding.Proxy'Access, Configure_Binding.Proxy'Access); overriding procedure Do_Get (Server : in Redirect_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Context_Path : constant String := Request.Get_Context_Path; begin Response.Send_Redirect (Context_Path & "/setup/install.html"); end Do_Get; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object is begin if Name = "database_name" then return Util.Beans.Objects.To_Object (From.Database.Get_Database); elsif Name = "database_server" then return Util.Beans.Objects.To_Object (From.Database.Get_Server); elsif Name = "database_port" then return Util.Beans.Objects.To_Object (From.Database.Get_Port); elsif Name = "database_user" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user")); elsif Name = "database_password" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password")); elsif Name = "database_driver" then return Util.Beans.Objects.To_Object (String '("sqlite")); end if; if From.Changed.Exists (Name) then return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name))); end if; declare Param : constant String := From.Config.Get (Name); begin return Util.Beans.Objects.To_Object (Param); end; exception when others => return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "database_name" then From.Database.Set_Database (Util.Beans.Objects.To_String (Value)); elsif Name = "database_server" then From.Database.Set_Server (Util.Beans.Objects.To_String (Value)); elsif Name = "database_port" then From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value)); elsif Name = "database_user" then From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value)); elsif Name = "database_password" then From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value)); elsif Name = "callback_url" then From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); From.Changed.Set ("facebook.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); From.Changed.Set ("google-plus.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); else From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Get the database connection string to be used by the application. -- ------------------------------ function Get_Database_URL (From : in Application) return String is use Ada.Strings.Unbounded; Result : Ada.Strings.Unbounded.Unbounded_String; begin Append (Result, "mysql://"); Append (Result, From.Database.Get_Server); if From.Database.Get_Port /= 0 then Append (Result, ":"); Append (Result, Util.Strings.Image (From.Database.Get_Port)); end if; Append (Result, "/"); Append (Result, From.Database.Get_Database); if From.Database.Get_Property ("user") /= "" then Append (Result, "?user="); Append (Result, From.Database.Get_Property ("user")); if From.Database.Get_Property ("password") /= "" then Append (Result, "&password="); Append (Result, From.Database.Get_Property ("password")); end if; end if; return To_String (Result); end Get_Database_URL; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Configure database"); -- dynamo create-database db sqlite:///atlas.db end Configure_Database; -- ------------------------------ -- Save the configuration. -- ------------------------------ procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Path : constant String := Ada.Strings.Unbounded.To_String (From.Path); New_File : constant String := Path & ".tmp"; Output : Ada.Text_IO.File_Type; procedure Read_Property (Line : in String) is Pos : constant Natural := Util.Strings.Index (Line, '='); begin if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then Ada.Text_IO.Put_Line (Output, Line); return; end if; Ada.Text_IO.Put (Output, Line (Line'First .. Pos)); Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1))); end Read_Property; begin Log.Info ("Saving configuration file {0}", Path); From.Changed.Set ("database", From.Get_Database_URL); Ada.Text_IO.Create (File => Output, Name => New_File); Util.Files.Read_File (Path, Read_Property'Access); Ada.Text_IO.Close (Output); Ada.Directories.Delete_File (Path); Ada.Directories.Rename (Old_Name => New_File, New_Name => Path); end Save; -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Finish configuration"); From.Done := True; end Finish; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Enter in the application setup -- ------------------------------ procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class) is begin Log.Info ("Entering configuration for {0}", Config); App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config); begin App.Config.Load_Properties (Config); Util.Log.Loggers.Initialize (Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file: {0}", Config); end; App.Initialize (App.Config, App.Factory); App.Set_Error_Page (ASF.Responses.SC_NOT_FOUND, "/setup/install.html"); App.Set_Global ("contextPath", App.Config.Get ("contextPath")); App.Set_Global ("setup", Util.Beans.Objects.To_Object (App'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Add_Servlet (Name => "redirect", Server => App.Redirect'Unchecked_Access); App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Mapping (Pattern => "*.html", Name => "redirect"); App.Add_Mapping (Pattern => "/setup/*.html", Name => "faces"); App.Add_Mapping (Pattern => "*.css", Name => "files"); App.Add_Mapping (Pattern => "*.js", Name => "files"); declare Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P); Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths); begin ASF.Applications.Main.Configs.Read_Configuration (App, Path); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Setup configuration file '{0}' does not exist", Path); end; declare URL : constant String := App.Config.Get ("google-plus.callback_url", ""); Pos : Natural := Util.Strings.Index (URL, '#'); begin if Pos > 0 then App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1)); end if; end; App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db")); Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access); while not App.Done loop delay 5.0; end loop; Server.Remove_Application (App'Unchecked_Access); end Setup; end AWA.Setup.Applications;
Implement the Do_Get procedure to redirect to the installation page Initialize the URL mapping to redirect to the installation page for any URL
Implement the Do_Get procedure to redirect to the installation page Initialize the URL mapping to redirect to the installation page for any URL
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
db060bb4a34735cf0be711cab1ff40b4df94c175
mat/src/mat-commands.adb
mat/src/mat-commands.adb
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread)); Ada.Text_IO.Set_Col (50); Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; begin MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Size)); Ada.Text_IO.Set_Col (20); Ada.Text_IO.Put (Natural'Image (Info.Count)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put_Line (MAT.Types.Target_Size'Image (Total)); end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Ada.Text_IO.Put_Line ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); end MAT.Commands;
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; with MAT.Consoles; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread)); Ada.Text_IO.Set_Col (50); Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25); Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.End_Title; MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Console.Start_Row; Console.Print_Size (MAT.Consoles.F_SIZE, Size); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count); Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total); Console.End_Row; end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Ada.Text_IO.Put_Line ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); end MAT.Commands;
Use the console operation to print the size of memory slots
Use the console operation to print the size of memory slots
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ec510785e206f2d49c42e43e2fbb4a1271fd1a27
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_FRAME_ID, F_FRAME_ADDR); type Notice_Type is (N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT, F_FRAME_ID, F_FRAME_ADDR); type Notice_Type is (N_HELP, N_PID_INFO, N_DURATION, N_PATH_INFO); type Justify_Type is (J_LEFT, -- Justify left |item | J_RIGHT, -- Justify right | item| J_CENTER, -- Justify center | item | J_RIGHT_NO_FILL -- Justify right |item| ); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Define the N_HELP notice type
Define the N_HELP notice type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a2fa06ce129b26c2f2e9515823f59087d8455f5d
src/sys/os-netbsd32/util-systems-constants.ads
src/sys/os-netbsd32/util-systems-constants.ads
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Constants is pragma Pure; -- Flags used when opening a file with open/creat. O_RDONLY : constant Interfaces.C.int := 8#000000#; O_WRONLY : constant Interfaces.C.int := 8#000001#; O_RDWR : constant Interfaces.C.int := 8#000002#; O_CREAT : constant Interfaces.C.int := 8#001000#; O_EXCL : constant Interfaces.C.int := 8#004000#; O_TRUNC : constant Interfaces.C.int := 8#002000#; O_APPEND : constant Interfaces.C.int := 8#000010#; O_CLOEXEC : constant Interfaces.C.int := 8#20000000#; O_SYNC : constant Interfaces.C.int := 8#000200#; O_DIRECT : constant Interfaces.C.int := 8#2000000#; O_NONBLOCK : constant Interfaces.C.int := 8#000004#; -- Flags used by fcntl F_SETFL : constant Interfaces.C.int := 4; F_GETFL : constant Interfaces.C.int := 3; FD_CLOEXEC : constant Interfaces.C.int := 1; -- Flags used by dlopen RTLD_LAZY : constant Interfaces.C.int := 8#000001#; RTLD_NOW : constant Interfaces.C.int := 8#000002#; RTLD_NOLOAD : constant Interfaces.C.int := 8#020000#; RTLD_DEEPBIND : constant Interfaces.C.int := 8#000000#; RTLD_GLOBAL : constant Interfaces.C.int := 8#000400#; RTLD_LOCAL : constant Interfaces.C.int := 8#001000#; RTLD_NODELETE : constant Interfaces.C.int := 8#010000#; DLL_OPTIONS : constant String := ""; end Util.Systems.Constants;
-- Generated by utildgen.c from system includes with Interfaces.C; package Util.Systems.Constants is pragma Pure; -- Flags used when opening a file with open/creat. O_RDONLY : constant Interfaces.C.int := 8#000000#; O_WRONLY : constant Interfaces.C.int := 8#000001#; O_RDWR : constant Interfaces.C.int := 8#000002#; O_CREAT : constant Interfaces.C.int := 8#001000#; O_EXCL : constant Interfaces.C.int := 8#004000#; O_TRUNC : constant Interfaces.C.int := 8#002000#; O_APPEND : constant Interfaces.C.int := 8#000010#; O_CLOEXEC : constant Interfaces.C.int := 8#20000000#; O_SYNC : constant Interfaces.C.int := 8#000200#; O_DIRECT : constant Interfaces.C.int := 8#2000000#; O_NONBLOCK : constant Interfaces.C.int := 8#000004#; -- Flags used by fcntl F_SETFL : constant Interfaces.C.int := 4; F_GETFL : constant Interfaces.C.int := 3; FD_CLOEXEC : constant Interfaces.C.int := 1; -- Flags used by dlopen RTLD_LAZY : constant Interfaces.C.int := 8#000001#; RTLD_NOW : constant Interfaces.C.int := 8#000002#; RTLD_NOLOAD : constant Interfaces.C.int := 8#020000#; RTLD_DEEPBIND : constant Interfaces.C.int := 8#000000#; RTLD_GLOBAL : constant Interfaces.C.int := 8#000400#; RTLD_LOCAL : constant Interfaces.C.int := 8#001000#; RTLD_NODELETE : constant Interfaces.C.int := 8#010000#; DLL_OPTIONS : constant String := ""; SYMBOL_PREFIX : constant String := ""; end Util.Systems.Constants;
Declare SYMBOL_PREFIX
Declare SYMBOL_PREFIX
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1633464161cb03366ae6a0cf9e582865c963a285
src/http/util-http-clients.ads
src/http/util-http-clients.ads
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- 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.Finalization; with Util.Http.Cookies; -- == Client == -- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send -- requests to an HTTP server. -- -- === GET request === -- To retrieve a content using the HTTP GET operation, a client instance must be created. -- The response is returned in a specific object that must therefore be declared: -- -- Http : Util.Http.Clients.Client; -- Response : Util.Http.Clients.Response; -- -- Before invoking the GET operation, the client can setup a number of HTTP headers. -- -- Http.Add_Header ("X-Requested-By", "wget"); -- -- The GET operation is performed when the <tt>Get</tt> procedure is called: -- -- Http.Get ("http://www.google.com", Response); -- -- Once the response is received, the <tt>Response</tt> object contains the status of the -- HTTP response, the HTTP reply headers and the body. package Util.Http.Clients is Connection_Error : exception; -- ------------------------------ -- Http response -- ------------------------------ -- The <b>Response</b> type represents a response returned by an HTTP request. type Response is limited new Abstract_Response with private; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean; -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Reply : in Response; Name : in String) return String; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String); -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String); -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)); -- Get the response body as a string. overriding function Get_Body (Reply : in Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Response) return Natural; -- ------------------------------ -- Http client -- ------------------------------ -- The <b>Client</b> type allows to execute HTTP GET/POST requests. type Client is limited new Abstract_Request with private; type Client_Access is access all Client; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Request : in Client; Name : in String) return Boolean; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in Client; Name : in String) return String; -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String); -- Adds a header with the given name and value. -- This method allows headers to have multiple values. overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String); -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)); -- Removes all headers with the given name. procedure Remove_Header (Request : in out Client; Name : in String); -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie); -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class); -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); private subtype Http_Request is Abstract_Request; subtype Http_Request_Access is Abstract_Request_Access; subtype Http_Response is Abstract_Response; subtype Http_Response_Access is Abstract_Response_Access; type Http_Manager is interface; type Http_Manager_Access is access all Http_Manager'Class; procedure Create (Manager : in Http_Manager; Http : in out Client'Class) is abstract; procedure Do_Get (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Post (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; Default_Http_Manager : Http_Manager_Access; type Response is new Ada.Finalization.Limited_Controlled and Abstract_Response with record Delegate : Abstract_Response_Access; end record; -- Free the resource used by the response. overriding procedure Finalize (Reply : in out Response); type Client is new Ada.Finalization.Limited_Controlled and Abstract_Request with record Manager : Http_Manager_Access; Delegate : Http_Request_Access; end record; -- Initialize the client overriding procedure Initialize (Http : in out Client); overriding procedure Finalize (Http : in out Client); end Util.Http.Clients;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- 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.Finalization; with Util.Http.Cookies; -- == Client == -- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send -- requests to an HTTP server. -- -- === GET request === -- To retrieve a content using the HTTP GET operation, a client instance must be created. -- The response is returned in a specific object that must therefore be declared: -- -- Http : Util.Http.Clients.Client; -- Response : Util.Http.Clients.Response; -- -- Before invoking the GET operation, the client can setup a number of HTTP headers. -- -- Http.Add_Header ("X-Requested-By", "wget"); -- -- The GET operation is performed when the <tt>Get</tt> procedure is called: -- -- Http.Get ("http://www.google.com", Response); -- -- Once the response is received, the <tt>Response</tt> object contains the status of the -- HTTP response, the HTTP reply headers and the body. A response header can be obtained -- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>: -- -- Body : constant String := Response.Get_Body; -- package Util.Http.Clients is Connection_Error : exception; -- ------------------------------ -- Http response -- ------------------------------ -- The <b>Response</b> type represents a response returned by an HTTP request. type Response is limited new Abstract_Response with private; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean; -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Reply : in Response; Name : in String) return String; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String); -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String); -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)); -- Get the response body as a string. overriding function Get_Body (Reply : in Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Response) return Natural; -- ------------------------------ -- Http client -- ------------------------------ -- The <b>Client</b> type allows to execute HTTP GET/POST requests. type Client is limited new Abstract_Request with private; type Client_Access is access all Client; -- Returns a boolean indicating whether the named response header has already -- been set. overriding function Contains_Header (Request : in Client; Name : in String) return Boolean; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in Client; Name : in String) return String; -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String); -- Adds a header with the given name and value. -- This method allows headers to have multiple values. overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String); -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)); -- Removes all headers with the given name. procedure Remove_Header (Request : in out Client; Name : in String); -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie); -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class); -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class); private subtype Http_Request is Abstract_Request; subtype Http_Request_Access is Abstract_Request_Access; subtype Http_Response is Abstract_Response; subtype Http_Response_Access is Abstract_Response_Access; type Http_Manager is interface; type Http_Manager_Access is access all Http_Manager'Class; procedure Create (Manager : in Http_Manager; Http : in out Client'Class) is abstract; procedure Do_Get (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is abstract; procedure Do_Post (Manager : in Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is abstract; Default_Http_Manager : Http_Manager_Access; type Response is new Ada.Finalization.Limited_Controlled and Abstract_Response with record Delegate : Abstract_Response_Access; end record; -- Free the resource used by the response. overriding procedure Finalize (Reply : in out Response); type Client is new Ada.Finalization.Limited_Controlled and Abstract_Request with record Manager : Http_Manager_Access; Delegate : Http_Request_Access; end record; -- Initialize the client overriding procedure Initialize (Http : in out Client); overriding procedure Finalize (Http : in out Client); end Util.Http.Clients;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f8d3b9f172583bf719bac629aa9c5da6b97de780
awa/plugins/awa-wikis/src/awa-wikis-servlets.ads
awa/plugins/awa-wikis/src/awa-wikis-servlets.ads
----------------------------------------------------------------------- -- awa-wikis-servlets -- Serve files saved in the storage service -- 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 ASF.Servlets; with ASF.Requests; with ASF.Responses; package AWA.Wikis.Servlets is -- The <b>Storage_Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Image_Servlet is new ASF.Servlets.Servlet with private; -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. overriding procedure Initialize (Server : in out Image_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class); -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" overriding procedure Do_Get (Server : in Image_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); private type Image_Servlet is new ASF.Servlets.Servlet with null record; end AWA.Wikis.Servlets;
----------------------------------------------------------------------- -- awa-wikis-servlets -- Serve files saved in the storage service -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ADO; with ASF.Requests; with AWA.Storages.Servlets; package AWA.Wikis.Servlets is -- The <b>Storage_Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Image_Servlet is new AWA.Storages.Servlets.Storage_Servlet with private; -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. procedure Load (Server : in Image_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref); private type Image_Servlet is new AWA.Storages.Servlets.Storage_Servlet with null record; end AWA.Wikis.Servlets;
Implement the Image_Servlet by using the AWA storage servlet and overloading the Load procedure
Implement the Image_Servlet by using the AWA storage servlet and overloading the Load procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0b50dc469567388cd2ec2abf427a78ea636e9937
regtests/ado-statements-tests.adb
regtests/ado-statements-tests.adb
----------------------------------------------------------------------- -- ado-statements-tests -- Test statements package -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Utils; with ADO.Sessions; with Regtests.Statements.Model; package body ADO.Statements.Tests is use Util.Tests; procedure Populate (Tst : in out Test); function Get_Sum (T : in Test; Table : in String) return Natural; -- Test the query statement Get_Xxx operation for various types. generic type T (<>) is private; with function Get_Value (Stmt : in ADO.Statements.Query_Statement; Column : in Natural) return T is <>; Name : String; Column : String; procedure Test_Query_Get_Value_T (Tst : in out Test); procedure Populate (Tst : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); Tst.Assert (Item.Is_Inserted, "Item inserted in database"); end; end loop; DB.Commit; end Populate; -- ------------------------------ -- Test the query statement Get_Xxx operation for various types. -- ------------------------------ procedure Test_Query_Get_Value_T (Tst : in out Test) is Stmt : ADO.Statements.Query_Statement; DB : constant ADO.Sessions.Session := Regtests.Get_Database; begin Populate (Tst); -- Check that Get_Value raises an exception if the statement is invalid. begin declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name); end; exception when Invalid_Statement => null; end; -- Execute a query to fetch one column. Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1"); Stmt.Execute; -- Verify the query result and the Get_Value operation. Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for " & Name & ":" & Column); Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for " & Name & ":" & Column); Util.Tests.Assert_Equals (Tst, Column, Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)), "The query returns an invalid column name"); declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Stmt.Clear; end; end Test_Query_Get_Value_T; procedure Test_Query_Get_Int64 is new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value"); procedure Test_Query_Get_Integer is new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value"); procedure Test_Query_Get_Nullable_Integer is new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer, "Get_Nullable_Integer", "int_value"); procedure Test_Query_Get_Nullable_Entity_Type is new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type, "Get_Nullable_Entity_Type", "entity_value"); procedure Test_Query_Get_Natural is new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value"); procedure Test_Query_Get_Identifier is new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier, "Get_Identifier", "id_value"); procedure Test_Query_Get_Boolean is new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value"); procedure Test_Query_Get_String is new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value"); package Caller is new Util.Test_Caller (Test, "ADO.Statements"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Statements.Save", Test_Save'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64", Test_Query_Get_Int64'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer", Test_Query_Get_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer", Test_Query_Get_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural", Test_Query_Get_Natural'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier", Test_Query_Get_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean", Test_Query_Get_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_String", Test_Query_Get_String'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type", Test_Query_Get_Nullable_Entity_Type'Access); end Add_Tests; function Get_Sum (T : in Test; Table : in String) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table); begin Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table & " WHERE id IN (:ids)"); begin Stmt.Bind_Param ("ids", Ids); Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; -- ------------------------------ -- Test creation of several rows in test_table with different column type. -- ------------------------------ procedure Test_Save (T : in out Test) is First : constant Natural := Get_Sum (T, "test_table"); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; List : ADO.Utils.Identifier_Vector; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); List.Append (Item.Get_Id); end; end loop; DB.Commit; Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"), "The SUM query returns an invalid value for test_table"); Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List), "The SUM query returns an invalid value for test_table"); end Test_Save; end ADO.Statements.Tests;
----------------------------------------------------------------------- -- ado-statements-tests -- Test statements package -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Utils; with ADO.Sessions; with Regtests.Statements.Model; package body ADO.Statements.Tests is use Util.Tests; procedure Populate (Tst : in out Test); function Get_Sum (T : in Test; Table : in String) return Natural; -- Test the query statement Get_Xxx operation for various types. generic type T (<>) is private; with function Get_Value (Stmt : in ADO.Statements.Query_Statement; Column : in Natural) return T is <>; Name : String; Column : String; procedure Test_Query_Get_Value_T (Tst : in out Test); procedure Populate (Tst : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); Tst.Assert (Item.Is_Inserted, "Item inserted in database"); end; end loop; DB.Commit; end Populate; -- ------------------------------ -- Test the query statement Get_Xxx operation for various types. -- ------------------------------ procedure Test_Query_Get_Value_T (Tst : in out Test) is Stmt : ADO.Statements.Query_Statement; DB : constant ADO.Sessions.Session := Regtests.Get_Database; begin Populate (Tst); -- Check that Get_Value raises an exception if the statement is invalid. begin declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name); end; exception when Invalid_Statement => null; end; -- Execute a query to fetch one column. Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1"); Stmt.Execute; -- Verify the query result and the Get_Value operation. Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for " & Name & ":" & Column); Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for " & Name & ":" & Column); Util.Tests.Assert_Equals (Tst, Column, Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)), "The query returns an invalid column name"); declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Stmt.Clear; end; end Test_Query_Get_Value_T; procedure Test_Query_Get_Int64 is new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value"); procedure Test_Query_Get_Integer is new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value"); procedure Test_Query_Get_Nullable_Integer is new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer, "Get_Nullable_Integer", "int_value"); procedure Test_Query_Get_Nullable_Entity_Type is new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type, "Get_Nullable_Entity_Type", "entity_value"); procedure Test_Query_Get_Natural is new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value"); procedure Test_Query_Get_Identifier is new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier, "Get_Identifier", "id_value"); procedure Test_Query_Get_Boolean is new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value"); procedure Test_Query_Get_String is new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value"); package Caller is new Util.Test_Caller (Test, "ADO.Statements"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Statements.Save", Test_Save'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64", Test_Query_Get_Int64'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer", Test_Query_Get_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer", Test_Query_Get_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural", Test_Query_Get_Natural'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier", Test_Query_Get_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean", Test_Query_Get_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_String", Test_Query_Get_String'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type", Test_Query_Get_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])", Test_Entity_Types'Access); end Add_Tests; function Get_Sum (T : in Test; Table : in String) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table); begin Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table & " WHERE id IN (:ids)"); begin Stmt.Bind_Param ("ids", Ids); Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; -- ------------------------------ -- Test creation of several rows in test_table with different column type. -- ------------------------------ procedure Test_Save (T : in out Test) is First : constant Natural := Get_Sum (T, "test_table"); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; List : ADO.Utils.Identifier_Vector; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); List.Append (Item.Get_Id); end; end loop; DB.Commit; Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"), "The SUM query returns an invalid value for test_table"); Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List), "The SUM query returns an invalid value for test_table"); end Test_Save; -- ------------------------------ -- Test queries using the $entity_type[] cache group. -- ------------------------------ procedure Test_Entity_Types (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Query_Statement; begin Stmt := DB.Create_Statement ("SELECT * FROM entity_type " & "WHERE entity_type.id = $entity_type[test_user]"); Stmt.Execute; Util.Tests.Assert_Equals (T, 1, Stmt.Get_Row_Count, "Query must return one row"); end Test_Entity_Types; end ADO.Statements.Tests;
Implement the Test_Entity_Types to test the $entity_type[table] expansion
Implement the Test_Entity_Types to test the $entity_type[table] expansion
Ada
apache-2.0
stcarrez/ada-ado
017314360c8ae183e9c31c6b36b666682983b87d
regtests/security-policies-tests.adb
regtests/security-policies-tests.adb
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Roles.Role_Policy'Class (P.all)'Access; declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Roles.Role_Policy'Class (P.all)'Access; Admin_Perm := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; with Security.Policies.Roles; with Security.Permissions.Tests; package body Security.Policies.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Policies"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)", Test_Read_Empty_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy", Test_Get_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy", Test_Read_Policy'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles", Test_Set_Roles'Access); Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)", Test_Set_Invalid_Roles'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Get the roles assigned to the user. -- ------------------------------ function Get_Roles (User : in Test_Principal) return Roles.Role_Map is begin return User.Roles; end Get_Roles; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Set_Roles -- ------------------------------ procedure Test_Set_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Admin : Role_Type; Manager : Role_Type; Map : Role_Map := (others => False); begin M.Create_Role (Name => "manager", Role => Manager); M.Create_Role (Name => "admin", Role => Admin); Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name"); T.Assert (not Map (Admin), "The admin role must not set in the map"); M.Set_Roles ("admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (not Map (Manager), "The manager role must not be set in the map"); Map := (others => False); M.Set_Roles ("manager,admin", Map); T.Assert (Map (Admin), "The admin role is not set in the map"); T.Assert (Map (Manager), "The manager role is not set in the map"); end Test_Set_Roles; -- ------------------------------ -- Test Set_Roles on an invalid role name -- ------------------------------ procedure Test_Set_Invalid_Roles (T : in out Test) is use Security.Policies.Roles; M : Security.Policies.Roles.Role_Policy; Map : Role_Map := (others => False); begin M.Set_Roles ("manager,admin", Map); T.Assert (False, "No exception was raised"); exception when E : Security.Policies.Roles.Invalid_Name => null; end Test_Set_Invalid_Roles; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Policies.Policy_Manager (1); -- Perm : Permissions.Permission_Type; User : Test_Principal; begin -- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); null; end Test_Has_Permission; procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager; Name : in String) is Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Manager.Add_Policy (R.all'Access); Manager.Add_Policy (U.all'Access); Manager.Read_Policy (Util.Files.Compose (Path, Name)); end Configure_Policy; -- ------------------------------ -- Test the Get_Policy, Get_Role_Policy and Add_Policy operations. -- ------------------------------ procedure Test_Get_Role_Policy (T : in out Test) is use type Roles.Role_Policy_Access; M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P = null, "Get_Policy succeeded"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R = null, "Get_Role_Policy succeeded"); R := new Roles.Role_Policy; M.Add_Policy (R.all'Access); P := M.Get_Policy (Security.Policies.Roles.NAME); T.Assert (P /= null, "Role policy not found"); T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy"); R := Security.Policies.Roles.Get_Role_Policy (M); T.Assert (R /= null, "Get_Role_Policy should not return null"); end Test_Get_Role_Policy; -- ------------------------------ -- Test reading an empty policy file -- ------------------------------ procedure Test_Read_Empty_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; begin Configure_Policy (M, "empty.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); declare Admin : Policies.Roles.Role_Type; begin Admin := R.Find_Role ("admin"); T.Fail ("'admin' role was returned"); exception when Security.Policies.Roles.Invalid_Name => null; end; T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission), "Has_Permission (admin) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission), "Has_Permission (create) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission), "Has_Permission (update) failed for empty policy"); T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission), "Has_Permission (delete) failed for empty policy"); end Test_Read_Empty_Policy; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Policies.Policy_Manager (Max_Policies => 2); User : aliased Test_Principal; Admin_Perm : Policies.Roles.Role_Type; Manager_Perm : Policies.Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy; begin Configure_Policy (M, "simple-policy.xml"); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); User.Roles (Admin_Perm) := True; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare use Security.Permissions.Tests; S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Policies.Policy_Manager (2); User : aliased Test_Principal; Admin_Perm : Roles.Role_Type; Context : aliased Security.Contexts.Security_Context; P : Security.Policies.Policy_Access; R : Security.Policies.Roles.Role_Policy_Access; U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy; begin Configure_Policy (M, File); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); R := Security.Policies.Roles.Get_Role_Policy (M); Admin_Perm := R.Find_Role (Role); declare P : constant URLs.URI_Permission (URI'Length) := URLs.URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (U.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Policies.Tests;
Add and implement a test for Get_Policy, Add_Policy, Get_Role_Policy
Add and implement a test for Get_Policy, Add_Policy, Get_Role_Policy
Ada
apache-2.0
Letractively/ada-security
73737434ed9439ad62caf6ef9b5ef3f385c516df
src/util-dates.adb
src/util-dates.adb
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Arithmetic; package body Util.Dates is -- ------------------------------ -- Split the date into a date record (See Ada.Calendar.Formatting.Split). -- ------------------------------ procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is begin Into.Date := Date; Into.Time_Zone := Time_Zone; Ada.Calendar.Formatting.Split (Date => Date, Year => Into.Year, Month => Into.Month, Day => Into.Month_Day, Hour => Into.Hour, Minute => Into.Minute, Second => Into.Second, Sub_Second => Into.Sub_Second, Leap_Second => Into.Leap_Second, Time_Zone => Time_Zone); Into.Day := Ada.Calendar.Formatting.Day_Of_Week (Date); end Split; -- ------------------------------ -- Returns true if the given year is a leap year. -- ------------------------------ function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is begin if Year mod 400 = 0 then return True; elsif Year mod 100 = 0 then return False; elsif Year mod 4 = 0 then return True; else return False; end if; end Is_Leap_Year; -- ------------------------------ -- Get the number of days in the given year. -- ------------------------------ function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count is begin if Is_Leap_Year (Year) then return 365; else return 366; end if; end Get_Day_Count; Month_Day_Count : constant array (Ada.Calendar.Month_Number) of Ada.Calendar.Arithmetic.Day_Count := (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31); -- ------------------------------ -- Get the number of days in the given month. -- ------------------------------ function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count is begin if Month /= 2 then return Month_Day_Count (Month); elsif Is_Leap_Year (Year) then return 29; else return 28; end if; end Get_Day_Count; -- ------------------------------ -- Get a time representing the given date at 00:00:00. -- ------------------------------ function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Day_Start; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_Start (D); end Get_Day_Start; -- ------------------------------ -- Get a time representing the given date at 23:59:59. -- ------------------------------ function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); end Get_Day_End; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_End (D); end Get_Day_End; -- ------------------------------ -- Get a time representing the beginning of the week at 00:00:00. -- ------------------------------ function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin if Day = Ada.Calendar.Formatting.Monday then return T; else return T - Day_Count (Day_Name'Pos (Day) - Day_Name'Pos (Monday)); end if; end Get_Week_Start; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_Start (D); end Get_Week_Start; -- ------------------------------ -- Get a time representing the end of the week at 23:59:99. -- ------------------------------ function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin -- End of week is 6 days + 23:59:59 if Day = Ada.Calendar.Formatting.Monday then return T + Day_Count (6); else return T + Day_Count (6 - (Day_Name'Pos (Day) - Day_Name'Pos (Monday))); end if; end Get_Week_End; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_End (D); end Get_Week_End; -- ------------------------------ -- Get a time representing the beginning of the month at 00:00:00. -- ------------------------------ function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Ada.Calendar.Day_Number'First, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Month_Start; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_Start (D); end Get_Month_Start; -- ------------------------------ -- Get a time representing the end of the month at 23:59:59. -- ------------------------------ function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is Last_Day : constant Ada.Calendar.Day_Number := Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month)); begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Last_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); end Get_Month_End; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_End (D); end Get_Month_End; end Util.Dates;
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Dates is -- ------------------------------ -- Split the date into a date record (See Ada.Calendar.Formatting.Split). -- ------------------------------ procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is begin Into.Date := Date; Into.Time_Zone := Time_Zone; Ada.Calendar.Formatting.Split (Date => Date, Year => Into.Year, Month => Into.Month, Day => Into.Month_Day, Hour => Into.Hour, Minute => Into.Minute, Second => Into.Second, Sub_Second => Into.Sub_Second, Leap_Second => Into.Leap_Second, Time_Zone => Time_Zone); Into.Day := Ada.Calendar.Formatting.Day_Of_Week (Date); end Split; -- ------------------------------ -- Returns true if the given year is a leap year. -- ------------------------------ function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is begin if Year mod 400 = 0 then return True; elsif Year mod 100 = 0 then return False; elsif Year mod 4 = 0 then return True; else return False; end if; end Is_Leap_Year; -- ------------------------------ -- Get the number of days in the given year. -- ------------------------------ function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count is begin if Is_Leap_Year (Year) then return 365; else return 366; end if; end Get_Day_Count; Month_Day_Count : constant array (Ada.Calendar.Month_Number) of Ada.Calendar.Arithmetic.Day_Count := (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31); -- ------------------------------ -- Get the number of days in the given month. -- ------------------------------ function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count is begin if Month /= 2 then return Month_Day_Count (Month); elsif Is_Leap_Year (Year) then return 29; else return 28; end if; end Get_Day_Count; -- ------------------------------ -- Get a time representing the given date at 00:00:00. -- ------------------------------ function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Day_Start; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_Start (D); end Get_Day_Start; -- ------------------------------ -- Get a time representing the given date at 23:59:59. -- ------------------------------ function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); end Get_Day_End; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Day_End (D); end Get_Day_End; -- ------------------------------ -- Get a time representing the beginning of the week at 00:00:00. -- ------------------------------ function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin if Day = Ada.Calendar.Formatting.Monday then return T; else return T - Day_Count (Day_Name'Pos (Day) - Day_Name'Pos (Monday)); end if; end Get_Week_Start; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_Start (D); end Get_Week_Start; -- ------------------------------ -- Get a time representing the end of the week at 23:59:99. -- ------------------------------ function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is use Ada.Calendar.Formatting; use Ada.Calendar.Arithmetic; T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year, Month => Date.Month, Day => Date.Month_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); Day : constant Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Day_Of_Week (T); begin -- End of week is 6 days + 23:59:59 if Day = Ada.Calendar.Formatting.Monday then return T + Day_Count (6); else return T + Day_Count (6 - (Day_Name'Pos (Day) - Day_Name'Pos (Monday))); end if; end Get_Week_End; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Week_End (D); end Get_Week_End; -- ------------------------------ -- Get a time representing the beginning of the month at 00:00:00. -- ------------------------------ function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Ada.Calendar.Day_Number'First, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0, Time_Zone => Date.Time_Zone); end Get_Month_Start; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_Start (D); end Get_Month_Start; -- ------------------------------ -- Get a time representing the end of the month at 23:59:59. -- ------------------------------ function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is Last_Day : constant Ada.Calendar.Day_Number := Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month)); begin return Ada.Calendar.Formatting.Time_Of (Year => Date.Year, Month => Date.Month, Day => Last_Day, Hour => 23, Minute => 59, Second => 59, Sub_Second => 0.999, Time_Zone => Date.Time_Zone); end Get_Month_End; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is D : Date_Record; begin Split (D, Date); return Get_Month_End (D); end Get_Month_End; end Util.Dates;
Fix some compilation warning
Fix some compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e5c92a1cafc051ae9eb4bf6768edfcf5a1fa93a5
awa/plugins/awa-storages/src/awa-storages.ads
awa/plugins/awa-storages/src/awa-storages.ads
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A content in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in the file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- -- Data.Set_Storage (Storage => AWA.Storages.Models.DATABASE); -- -- To save a file in the store, we can use the `Save` operation. It will read the file -- and put in in the corresponding persistent store (the database in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier: -- -- Service.Load (From => Id, Into => Data); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png] -- -- @include Storages.hbm.xml package AWA.Storages is end AWA.Storages;
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A content in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in the file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- -- Data.Set_Storage (Storage => AWA.Storages.Models.DATABASE); -- -- To save a file in the store, we can use the `Save` operation. It will read the file -- and put in in the corresponding persistent store (the database in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- === Local file === -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading locally we -- also indicate whether the file will be read or written. A file that is in `READ` mode -- can be shared by several tasks or processes. A file that is in `WRITE` mode will have -- a specific copy for the caller. An optional expiration parameter indicate when the -- local file representation can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png] -- -- @include Storages.hbm.xml package AWA.Storages is end AWA.Storages;
Update the documentation of the storage module
Update the documentation of the storage module
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8b5d25e31db8d6512fd58f41e26b389566d391fc
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Storages.Models; with ADO.Objects; with ADO.Sessions; with ADO.Statements; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Workspaces.Modules.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id, List => (ACL_Delete_Blog.Permission, ACL_Update_Post.Permission, ACL_Create_Post.Permission, ACL_Delete_Post.Permission)); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; -- ------------------------------ -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. -- ------------------------------ procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref) is pragma Unreferenced (Model); use type AWA.Storages.Models.Storage_Type; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement; Kind : AWA.Storages.Models.Storage_Type; begin if Width = Natural'Last or Height = Natural'Last then Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); elsif Width > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data); Query.Bind_Param ("width", Width); elsif Height > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data); Query.Bind_Param ("height", Height); else Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); end if; Query.Bind_Param ("post_id", Post_Id); Query.Bind_Param ("store_id", Image_Id); Query.Bind_Param ("user_id", User); Query.Execute; if not Query.Has_Elements then Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id)); raise ADO.Objects.NOT_FOUND; end if; Mime := Query.Get_Unbounded_String (0); Date := Query.Get_Time (1); Width := Query.Get_Natural (4); Height := Query.Get_Natural (5); Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3)); if Kind = AWA.Storages.Models.DATABASE then Into := Query.Get_Blob (6); else null; end if; end Load_Image; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Storages.Models; with ADO.Objects; with ADO.Sessions; with ADO.Statements; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Stat_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX); begin Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix)); end Configure; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Workspaces.Modules.Add_Permission (Session => DB, User => User, Entity => Blog, Workspace => WS.Get_Id, List => (ACL_Delete_Blog.Permission, ACL_Update_Post.Permission, ACL_Create_Post.Permission, ACL_Delete_Post.Permission)); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; -- ------------------------------ -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. -- ------------------------------ procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref) is pragma Unreferenced (Model); use type AWA.Storages.Models.Storage_Type; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Statements.Query_Statement; Kind : AWA.Storages.Models.Storage_Type; begin if Width = Natural'Last or Height = Natural'Last then Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); elsif Width > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data); Query.Bind_Param ("width", Width); elsif Height > 0 then Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data); Query.Bind_Param ("height", Height); else Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data); end if; Query.Bind_Param ("post_id", Post_Id); Query.Bind_Param ("store_id", Image_Id); Query.Bind_Param ("user_id", User); Query.Execute; if not Query.Has_Elements then Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id)); raise ADO.Objects.NOT_FOUND; end if; Mime := Query.Get_Unbounded_String (0); Date := Query.Get_Time (1); Width := Query.Get_Natural (4); Height := Query.Get_Natural (5); Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3)); if Kind = AWA.Storages.Models.DATABASE then Into := Query.Get_Blob (6); else null; end if; end Load_Image; end AWA.Blogs.Modules;
Implement the Configure procedure
Implement the Configure procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d96806dcea4f999cdd84f103032537eaa304d4c6
src/ado-connections.ads
src/ado-connections.ads
----------------------------------------------------------------------- -- ado-connections -- Database connections -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with ADO.Configs; with Util.Strings; with Util.Strings.Vectors; with Util.Refs; -- The `ADO.Connections` package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Connections is use ADO.Statements; -- Raised for all errors reported by the database. Database_Error : exception; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; subtype Driver_Index is ADO.Configs.Driver_Index; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new ADO.Configs.Configuration with null record; -- Get the driver index that corresponds to the driver for this database connection string. function Get_Driver (Config : in Configuration) return Driver_Index; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) with Post => not Result.Is_Null; -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is abstract with Post'Class => not Result.Is_Null; -- 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. procedure Create_Database (D : in out Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; end ADO.Connections;
----------------------------------------------------------------------- -- ado-connections -- Database connections -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with ADO.Configs; with Util.Strings; with Util.Strings.Vectors; with Util.Refs; -- The `ADO.Connections` package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Connections is use ADO.Statements; -- Raised for all errors reported by the database. Database_Error : exception; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; subtype Driver_Index is ADO.Configs.Driver_Index range 1 .. ADO.Configs.Driver_Index'Last; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new ADO.Configs.Configuration with null record; -- Get the driver index that corresponds to the driver for this database connection string. function Get_Driver (Config : in Configuration) return Driver_Index; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) with Post => not Result.Is_Null; -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is abstract with Post'Class => not Result.Is_Null; -- 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. procedure Create_Database (D : in out Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; end ADO.Connections;
Update Driver_Index type to exclude 0 value
Update Driver_Index type to exclude 0 value
Ada
apache-2.0
stcarrez/ada-ado
e1f39b910817471f22df47ec9a0eee590e32a611
mat/src/mat-commands.ads
mat/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- The options that can be configured through the command line. type Options_Type is record Interactive : Boolean := True; Graphical : Boolean := False; Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class; Options : in out Options_Type); end MAT.Commands;
Declare the Initialize_Options procedure and Options_Type type
Declare the Initialize_Options procedure and Options_Type type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4fa98df881b1f2bd0789b5378646662d4c6faa09
matp/src/memory/mat-memory.ads
matp/src/memory/mat-memory.ads
----------------------------------------------------------------------- -- Memory - Memory slot -- 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.Strings.Unbounded; with ELF; with MAT.Types; with MAT.Frames; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; Min_Addr : MAT.Types.Target_Addr := 0; Max_Addr : MAT.Types.Target_Addr := 0; end record; -- Description of a memory region. type Region_Info is record Start_Addr : MAT.Types.Target_Addr := 0; End_Addr : MAT.Types.Target_Addr := 0; Size : MAT.Types.Target_Size := 0; Flags : ELF.Elf32_Word := 0; Path : Ada.Strings.Unbounded.Unbounded_String; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- Define a map of <tt>Memory_Info</tt> keyed by the thread Id. -- Such map allows to give the list of threads and a summary of their allocation. use type MAT.Types.Target_Thread_Ref; package Memory_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref, Element_Type => Memory_Info); subtype Memory_Info_Map is Memory_Info_Maps.Map; subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor; type Frame_Info is record Thread : MAT.Types.Target_Thread_Ref; Memory : Memory_Info; end record; -- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address -- that performed the memory allocation directly or indirectly. package Frame_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Frame_Info); subtype Frame_Info_Map is Frame_Info_Maps.Map; subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor; package Region_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Region_Info); subtype Region_Info_Map is Region_Info_Maps.Map; subtype Region_Info_Cursor is Region_Info_Maps.Cursor; end MAT.Memory;
----------------------------------------------------------------------- -- Memory - Memory slot -- 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.Strings.Unbounded; with ELF; with MAT.Types; with MAT.Frames; with MAT.Events.Targets; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Event : MAT.Events.Targets.Event_Id_Type; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; Min_Addr : MAT.Types.Target_Addr := 0; Max_Addr : MAT.Types.Target_Addr := 0; end record; -- Description of a memory region. type Region_Info is record Start_Addr : MAT.Types.Target_Addr := 0; End_Addr : MAT.Types.Target_Addr := 0; Size : MAT.Types.Target_Size := 0; Flags : ELF.Elf32_Word := 0; Path : Ada.Strings.Unbounded.Unbounded_String; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; -- Define a map of <tt>Memory_Info</tt> keyed by the thread Id. -- Such map allows to give the list of threads and a summary of their allocation. use type MAT.Types.Target_Thread_Ref; package Memory_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Thread_Ref, Element_Type => Memory_Info); subtype Memory_Info_Map is Memory_Info_Maps.Map; subtype Memory_Info_Cursor is Memory_Info_Maps.Cursor; type Frame_Info is record Thread : MAT.Types.Target_Thread_Ref; Memory : Memory_Info; end record; -- Define a map of <tt>Frame_Info</tt> keyed by the backtrace function address -- that performed the memory allocation directly or indirectly. package Frame_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Frame_Info); subtype Frame_Info_Map is Frame_Info_Maps.Map; subtype Frame_Info_Cursor is Frame_Info_Maps.Cursor; package Region_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Region_Info); subtype Region_Info_Map is Region_Info_Maps.Map; subtype Region_Info_Cursor is Region_Info_Maps.Cursor; end MAT.Memory;
Add the event id in the Allocation record to keep information about the last event that alloc'ed a memory slot
Add the event id in the Allocation record to keep information about the last event that alloc'ed a memory slot
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e9fca3bfa9dc4e891b5d90ee4fb1b806ea679843
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, 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 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"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- Rename a file (the Ada.Directories.Rename does not allow to use the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); -- 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;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Chmod, "chmod"); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); -- 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 Sys_Chmod operation to change the permission of a file
Declare the Sys_Chmod operation to change the permission of a file
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9431dfb112483346b95abb67acf566d726d14693
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 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;
----------------------------------------------------------------------- -- 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"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- 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;
Fix compilation warning and declare Sys_Fchmod operation
Fix compilation warning and declare Sys_Fchmod operation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
80899d3ebdb97e8191ff022f1dfcdfe7c90ea675
src/util-properties-discrete.adb
src/util-properties-discrete.adb
----------------------------------------------------------------------- -- discrete properties -- Generic package for get/set of discrete properties -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Properties.Discrete is -- ------------------------------ -- Get the property value -- ------------------------------ function Get (Self : in Manager'Class; Name : in String) return Property_Type is Val : constant String := -Get (Self, Name); begin return Property_Type'Value (Val); end Get; -- ------------------------------ -- Get the property value. -- Return the default if the property does not exist. -- ------------------------------ function Get (Self : in Manager'Class; Name : in String; Default : in Property_Type) return Property_Type is begin return Get (Self, Name); exception when others => return Default; end Get; -- ------------------------------ -- Set the property value -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Value : in Property_Type) is begin Set (Self, Name, Property_Type'Image (Value)); end Set; end Util.Properties.Discrete;
----------------------------------------------------------------------- -- util-properties-discrete -- Generic package for get/set of discrete properties -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Properties.Discrete is -- ------------------------------ -- Get the property value -- ------------------------------ function Get (Self : in Manager'Class; Name : in String) return Property_Type is Val : constant String := -Get (Self, Name); begin return Property_Type'Value (Val); end Get; -- ------------------------------ -- Get the property value. -- Return the default if the property does not exist. -- ------------------------------ function Get (Self : in Manager'Class; Name : in String; Default : in Property_Type) return Property_Type is begin return Get (Self, Name); exception when others => return Default; end Get; -- ------------------------------ -- Set the property value -- ------------------------------ procedure Set (Self : in out Manager'Class; Name : in String; Value : in Property_Type) is begin Set (Self, Name, Property_Type'Image (Value)); end Set; end Util.Properties.Discrete;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7a2cc554ff9a98f2d5653b58ab99dc1216e3e5d5
ARM/STMicro/STM32/examples/draw/src/draw.adb
ARM/STMicro/STM32/examples/draw/src/draw.adb
------------------------------------------------------------------------------ -- -- -- GNAT EXAMPLE -- -- -- -- Copyright (C) 2015, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- A very simple draw application. -- Use your finger to draw pixels. with STM32.LCD; use STM32.LCD; with STM32.DMA2D.Interrupt; use STM32.DMA2D; with STM32.Touch_Panel; use STM32.Touch_Panel; with STM32.Button; with Bitmapped_Drawing; use Bitmapped_Drawing; with Double_Buffer; use Double_Buffer; procedure Draw is FG_Buffer : DMA2D_Buffer; ----------- -- Clear -- ----------- procedure Clear is begin DMA2D_Fill (FG_Buffer, Color => (Alpha => 255, others => 64)); end Clear; Red : constant DMA2D_Color := (Alpha => 255, Red => 255, Green => 0, Blue => 0); begin -- Initialize LCD STM32.LCD.Initialize (Pixel_Fmt_RGB888); STM32.DMA2D.Interrupt.Initialize; Double_Buffer.Initialize (Layer_Background => Layer_Single_Buffer, Layer_Foreground => Layer_Inactive); FG_Buffer := Double_Buffer.Get_Visible_Buffer (Background); -- Initialize touch panel STM32.Touch_Panel.Initialize; -- Initialize button STM32.Button.Initialize; -- Clear LCD (set background) Clear; -- The application: set pixel where the finger is (so that you -- cannot see what you are drawing). loop if STM32.Button.Has_Been_Pressed then Clear; else declare State : constant TP_State := Get_State; begin for Touch of State loop -- Workaround some strange readings from the STM32F429 TP if Touch.X < FG_Buffer.Width - 1 then Fill_Circle (FG_Buffer, (Touch.X, Touch.Y), Touch.Weight / 4, Red); end if; end loop; end; end if; end loop; end Draw;
------------------------------------------------------------------------------ -- -- -- GNAT EXAMPLE -- -- -- -- Copyright (C) 2015, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- A very simple draw application. -- Use your finger to draw pixels. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); -- The "last chance handler" is the user-defined routine that is called when -- an exception is propagated. We need it in the executable, therefore it -- must be somewhere in the closure of the context clauses. with STM32.LCD; use STM32.LCD; with STM32.DMA2D.Interrupt; use STM32.DMA2D; with STM32.Touch_Panel; use STM32.Touch_Panel; with STM32.Button; with Bitmapped_Drawing; use Bitmapped_Drawing; with Double_Buffer; use Double_Buffer; procedure Draw is FG_Buffer : DMA2D_Buffer; ----------- -- Clear -- ----------- procedure Clear is begin DMA2D_Fill (FG_Buffer, Color => (Alpha => 255, others => 64)); end Clear; Red : constant DMA2D_Color := (Alpha => 255, Red => 255, Green => 0, Blue => 0); begin -- Initialize LCD STM32.LCD.Initialize (Pixel_Fmt_RGB888); STM32.DMA2D.Interrupt.Initialize; Double_Buffer.Initialize (Layer_Background => Layer_Single_Buffer, Layer_Foreground => Layer_Inactive); FG_Buffer := Double_Buffer.Get_Visible_Buffer (Background); -- Initialize touch panel STM32.Touch_Panel.Initialize; -- Initialize button STM32.Button.Initialize; -- Clear LCD (set background) Clear; -- The application: set pixel where the finger is (so that you -- cannot see what you are drawing). loop if STM32.Button.Has_Been_Pressed then Clear; else declare State : constant TP_State := Get_State; begin for Touch of State loop -- Workaround some strange readings from the STM32F429 TP if Touch.X < FG_Buffer.Width - 1 then Fill_Circle (FG_Buffer, (Touch.X, Touch.Y), Touch.Weight / 4, Red); end if; end loop; end; end if; end loop; end Draw;
Make sure the last chance handler is included by the draw example.
Make sure the last chance handler is included by the draw example.
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
0323d352d90970d5a86901fd42cf1cf0010eb12c
examples/usart_interruptive_echo/src/main.adb
examples/usart_interruptive_echo/src/main.adb
#if MCU="ATMEGA2560" then with AVR.USART; with AVR.INTERRUPTS; #end if; procedure Main is -- Out_Flag_Char : Character; begin #if MCU="ATMEGA2560" then AVR.INTERRUPTS.Disable; AVR.USART.Initialize (In_Port => AVR.USART.USART1, In_Setup => (Sync_Mode => AVR.USART.ASYNCHRONOUS, Double_Speed => True, Baud_Rate => 9600, Data_Bits => AVR.USART.BITS_8, Parity => AVR.USART.NONE, Stop_Bits => 1, Model => AVR.USART.INTERRUPTIVE)); AVR.USART.Put_Line (Port => AVR.USART.USART1, Data => "#### Initialization ok. ####"); AVR.INTERRUPTS.Enable; loop -- Out_Flag_Char := AVR.USART.Get; -- AVR.USART.Put -- (Port => AVR.USART.USART1, -- Data => Out_Flag_Char); null; end loop; #else null; #end if; end Main;
#if MCU="ATMEGA2560" then with AVR.USART; with AVR.INTERRUPTS; #end if; procedure Main is Counter : Long_Integer := 0; Out_Buffer : AVR.USART.Buffer_64_Type; begin #if MCU="ATMEGA2560" then AVR.INTERRUPTS.Disable; AVR.USART.Initialize (In_Port => AVR.USART.USART1, In_Setup => (Sync_Mode => AVR.USART.ASYNCHRONOUS, Double_Speed => True, Baud_Rate => 9600, Data_Bits => AVR.USART.BITS_8, Parity => AVR.USART.NONE, Stop_Bits => 1, Model => AVR.USART.INTERRUPTIVE)); AVR.USART.Put_Line (Port => AVR.USART.USART1, Data => "#### Initialization ok. ####"); AVR.INTERRUPTS.Enable; loop Counter := Counter + 1; if AVR.USART.Get_Raw_Buffer (In_Port => AVR.USART.USART1, Out_Data => Out_Buffer) then AVR.USART.Put_Buffer (In_Port => AVR.USART.USART1); end if; end loop; #else null; #end if; end Main;
Read from usart1 in interruptive mode.
Read from usart1 in interruptive mode.
Ada
mit
pvrego/adaino,pvrego/adaino
912983f291a4884da42f77e3969671ae69f673f9
src/http/aws/util-http-clients-web.adb
src/http/aws/util-http-clients-web.adb
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers.Set; with AWS.Messages; with Util.Log.Loggers; package body Util.Http.Clients.Web is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web"); Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; overriding procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Get {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Get; overriding procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Post {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Post; overriding procedure Do_Put (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Put {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Put; overriding procedure Do_Delete (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Delete {0}", URI); Reply.Delegate := Rep.all'Access; -- Rep.Data := AWS.Client.Delete (URL => URI, Data => "", Headers => Req.Headers, -- Timeouts => Req.Timeouts); raise Program_Error with "Delete is not supported by AWS and there is no easy conditional" & " compilation in Ada to enable Delete support for the latest AWS version. " & "For now, you have to use curl, or install the latest AWS version and then " & "uncomment the AWS.Client.Delete call and remove this exception."; end Do_Delete; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ overriding procedure Set_Timeout (Manager : in AWS_Http_Manager; Http : in Client'Class; Timeout : in Duration) is begin AWS_Http_Request'Class (Http.Delegate.all).Timeouts := AWS.Client.Timeouts (Connect => Timeout, Send => Timeout, Receive => Timeout, Response => Timeout); end Set_Timeout; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWS.Messages; with Util.Log.Loggers; package body Util.Http.Clients.Web is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web"); Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; overriding procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Get {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Get; overriding procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Post {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Post; overriding procedure Do_Put (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Put {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Put (URL => URI, Data => Data, Headers => Req.Headers, Timeouts => Req.Timeouts); end Do_Put; overriding procedure Do_Delete (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager, Http); -- Req : constant AWS_Http_Request_Access -- := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Delete {0}", URI); Reply.Delegate := Rep.all'Access; -- Rep.Data := AWS.Client.Delete (URL => URI, Data => "", Headers => Req.Headers, -- Timeouts => Req.Timeouts); raise Program_Error with "Delete is not supported by AWS and there is no easy conditional" & " compilation in Ada to enable Delete support for the latest AWS version. " & "For now, you have to use curl, or install the latest AWS version and then " & "uncomment the AWS.Client.Delete call and remove this exception."; end Do_Delete; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ overriding procedure Set_Timeout (Manager : in AWS_Http_Manager; Http : in Client'Class; Timeout : in Duration) is pragma Unreferenced (Manager); begin AWS_Http_Request'Class (Http.Delegate.all).Timeouts := AWS.Client.Timeouts (Connect => Timeout, Send => Timeout, Receive => Timeout, Response => Timeout); end Set_Timeout; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is Values : constant AWS.Headers.VString_Array := AWS.Headers.Get_Values (Http.Headers, Name); begin return Values'Length > 0; end Contains_Header; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is Values : constant AWS.Headers.VString_Array := AWS.Headers.Get_Values (Request.Headers, Name); begin if Values'Length > 0 then return Ada.Strings.Unbounded.To_String (Values (Values'First)); else return ""; end if; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
Implement Contains_Header and Get_Header Avoid using the deprecated AWS.Headers.Set package
Implement Contains_Header and Get_Header Avoid using the deprecated AWS.Headers.Set package
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8dc1ad7196f39f70c68a075d476fd36e1243dcdc
awa/plugins/awa-settings/src/awa-settings-modules.adb
awa/plugins/awa-settings/src/awa-settings-modules.adb
----------------------------------------------------------------------- -- awa-awa-settings-modules -- Module awa-settings -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWA.Services.Contexts; with AWA.Modules.Get; with Util.Log.Loggers; package body AWA.Settings.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Awa-settings.Module"); package ASC renames AWA.Services.Contexts; -- Set the user setting with the given name in the setting manager cache -- and in the database. procedure Set (Manager : in out Setting_Manager; Name : in String; Value : in String) is begin Manager.Data.Set (Name, Value); end Set; -- Get the user setting with the given name from the setting manager cache. -- Load the user setting from the database if necessary. procedure Get (Manager : in out Setting_Manager; Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is begin Manager.Data.Get (Name, Default, Value); end Get; function Current return Setting_Manager_Access is Ctx : ASC.Service_Context_Access := ASC.Current; begin -- Settings := Ctx.Get_Session_Attribute ("AWA.Settings"); -- if Settings = null then -- -- create -- null; -- end if; return null; end Current; -- ------------------------------ -- Initialize the awa-settings module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Setting_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the awa-settings module"); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the awa-settings module. -- ------------------------------ function Get_Setting_Module return Setting_Module_Access is function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME); begin return Get; end Get_Setting_Module; procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data, Name => Setting_Data_Access); use Ada.Strings.Unbounded; protected body Settings is procedure Get (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is Item : Setting_Data_Access := First; Previous : Setting_Data_Access := null; begin while Item /= null loop if Item.Name = Name then Value := Item.Value; if Previous /= null then Previous.Next_Setting := Item.Next_Setting; First := Item; end if; return; end if; Previous := Item; Item := Item.Next_Setting; end loop; Value := Ada.Strings.Unbounded.To_Unbounded_String (Default); end Get; procedure Set (Name : in String; Value : in String) is Item : Setting_Data_Access := First; Previous : Setting_Data_Access := null; begin while Item /= null loop if Item.Name = Name then if Previous /= null then Previous.Next_Setting := Item.Next_Setting; First := Item; end if; if Item.Value = Value then return; end if; Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value); return; end if; Previous := Item; Item := Item.Next_Setting; end loop; end Set; procedure Clear is begin while First /= null loop declare Item : Setting_Data_Access := First; begin First := Item.Next_Setting; Free (Item); end; end loop; end Clear; end Settings; end AWA.Settings.Modules;
----------------------------------------------------------------------- -- awa-awa-settings-modules -- Module awa-settings -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWA.Services.Contexts; with AWA.Modules.Get; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Beans.Basic; package body AWA.Settings.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Awa-settings.Module"); package ASC renames AWA.Services.Contexts; -- Set the user setting with the given name in the setting manager cache -- and in the database. procedure Set (Manager : in out Setting_Manager; Name : in String; Value : in String) is begin Manager.Data.Set (Name, Value); end Set; -- Get the user setting with the given name from the setting manager cache. -- Load the user setting from the database if necessary. procedure Get (Manager : in out Setting_Manager; Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is begin Manager.Data.Get (Name, Default, Value); end Get; function Current return Setting_Manager_Access is Ctx : ASC.Service_Context_Access := ASC.Current; Obj : Util.Beans.Objects.Object := Ctx.Get_Session_Attribute ("AWA.Settings"); Bean : access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Obj); begin if Bean = null or else not (Bean.all in Setting_Manager'Class) then declare Mgr : Setting_Manager_Access := new Setting_Manager; begin Obj := Util.Beans.Objects.To_Object (Mgr.all'Access); Ctx.Set_Session_Attribute ("AWA.Settings", Obj); return Mgr; end; else return Setting_Manager'Class (Bean.all)'Access; end if; end Current; -- ------------------------------ -- Initialize the awa-settings module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Setting_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the awa-settings module"); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the awa-settings module. -- ------------------------------ function Get_Setting_Module return Setting_Module_Access is function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME); begin return Get; end Get_Setting_Module; procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data, Name => Setting_Data_Access); use Ada.Strings.Unbounded; protected body Settings is procedure Get (Name : in String; Default : in String; Value : out Ada.Strings.Unbounded.Unbounded_String) is Item : Setting_Data_Access := First; Previous : Setting_Data_Access := null; begin while Item /= null loop if Item.Name = Name then Value := Item.Value; if Previous /= null then Previous.Next_Setting := Item.Next_Setting; First := Item; end if; return; end if; Previous := Item; Item := Item.Next_Setting; end loop; Value := Ada.Strings.Unbounded.To_Unbounded_String (Default); end Get; procedure Set (Name : in String; Value : in String) is Item : Setting_Data_Access := First; Previous : Setting_Data_Access := null; begin while Item /= null loop if Item.Name = Name then if Previous /= null then Previous.Next_Setting := Item.Next_Setting; First := Item; end if; if Item.Value = Value then return; end if; Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value); return; end if; Previous := Item; Item := Item.Next_Setting; end loop; end Set; procedure Clear is begin while First /= null loop declare Item : Setting_Data_Access := First; begin First := Item.Next_Setting; Free (Item); end; end loop; end Clear; end Settings; end AWA.Settings.Modules;
Create the setting manager if there is none and save it in the HTTP session
Create the setting manager if there is none and save it in the HTTP session
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9c2ffadf3fb29c01739edc1509e3cb45a0dedd73
src/babel-base.ads
src/babel-base.ads
----------------------------------------------------------------------- -- babel-base -- File filters -- 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 Babel.Base is end Babel.Base;
----------------------------------------------------------------------- -- babel-base -- Database for files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO; package Babel.Base is type Database is abstract new Ada.Finalization.Limited_Controlled with private; private type Database is abstract new Ada.Finalization.Limited_Controlled with record Name : Integer; end record; end Babel.Base;
Define the abstract Database type to represent the database of backup files
Define the abstract Database type to represent the database of backup files
Ada
apache-2.0
stcarrez/babel
8fb6a609b12faff4f5ab47709eee03243520d772
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER); type Notice_Type is (N_PID_INFO, N_DURATION, N_PATH_INFO); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER, F_ID, F_OLD_ADDR, F_TIME, F_EVENT); type Notice_Type is (N_PID_INFO, N_DURATION, N_PATH_INFO); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the time tick as a duration and print it for the given field. procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Declare the Print_Duration operation to format a time
Declare the Print_Duration operation to format a time
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
33aace541b9c30e9eeaacb25dff0c09bf397fbfc
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Declare the Notice procedure to report some information message
Declare the Notice procedure to report some information message
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
11714407a1657fdd2c16b3e73a4717c4390181b3
ada/reader.adb
ada/reader.adb
with Ada.IO_Exceptions; with Ada.Characters.Latin_1; with Ada.Strings.Maps.Constants; with Ada.Strings.Unbounded; with Ada.Text_IO; with Opentoken.Recognizer.Character_Set; with Opentoken.Recognizer.Identifier; with Opentoken.Recognizer.Integer; with Opentoken.Recognizer.Keyword; with Opentoken.Recognizer.Line_Comment; with Opentoken.Recognizer.Separator; with Opentoken.Recognizer.Single_Character_Set; with Opentoken.Recognizer.String; with OpenToken.Text_Feeder.String; with Opentoken.Token.Enumerated.Analyzer; package body Reader is type Lexemes is (Int, Sym, Nil, True_Tok, False_Tok, Exp_Tok, Str, Atom, Whitespace, Comment); package Lisp_Tokens is new Opentoken.Token.Enumerated (Lexemes); package Tokenizer is new Lisp_Tokens.Analyzer; Exp_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Separator.Get ("**")); Nil_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("nil")); True_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("true")); False_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("false")); ID_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Identifier.Get); Int_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Integer.Get); String_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.String.Get); -- Atom definition Start_Chars : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.Constants.Letter_Set; Body_Chars : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps."or" (Ada.Strings.Maps.Constants.Alphanumeric_Set, Ada.Strings.Maps.To_Set ('-')); Atom_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Identifier.Get (Start_Chars, Body_Chars)); Lisp_Syms : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set ("[]{}()'`~^@+-*/"); Sym_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Single_Character_Set.Get (Lisp_Syms)); Lisp_Whitespace : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (Ada.Characters.Latin_1.HT & Ada.Characters.Latin_1.Space & Ada.Characters.Latin_1.Comma); Whitesp_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Character_Set.Get (Lisp_Whitespace)); Comment_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Line_Comment.Get (";")); Syntax : constant Tokenizer.Syntax := (Int => Int_Recognizer, Sym => Sym_Recognizer, Nil => Nil_Recognizer, True_Tok => True_Recognizer, False_Tok => False_Recognizer, Exp_Tok => Exp_Recognizer, Str => String_Recognizer, Atom => Atom_Recognizer, Whitespace => Whitesp_Recognizer, Comment => Comment_Recognizer --, ); Input_Feeder : aliased OpenToken.Text_Feeder.String.Instance; Analyzer : Tokenizer.Instance := Tokenizer.Initialize (Syntax, Input_Feeder'access); function Get_Token_String return String is begin return Tokenizer.Lexeme (Analyzer); end Get_Token_String; function Get_Token_Char return Character is S : String := Tokenizer.Lexeme (Analyzer); begin return S(S'First); end Get_Token_Char; function Get_Token return Types.Mal_Type_Access is Res : Types.Mal_Type_Access; begin Tokenizer.Find_Next (Analyzer); case Tokenizer.ID (Analyzer) is when Int => Res := new Types.Mal_Type' (Sym_Type => Types.Int, Int_Val => Integer'Value (Get_Token_String)); when Sym => Res := new Types.Mal_Type' (Sym_Type => Types.Sym, Symbol => Get_Token_Char); when Nil => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when True_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when False_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Exp_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Str => Res := new Types.Mal_Type' (Sym_Type => Types.Str, The_String => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Atom => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Whitespace | Comment => null; end case; return Res; end Get_Token; -- Parsing function Read_Form return Types.Mal_Type_Access; function Read_List return Types.Mal_Type_Access is use types; List_MT, MTA : Types.Mal_Type_Access; begin List_MT := new Types.Mal_Type' (Sym_Type => Types.List, The_List => Types.Lists.Empty_List); loop MTA := Read_Form; exit when MTA = null or else MTA.all = (Sym_Type => Sym, Symbol => ')'); Types.Lists.Append (List_MT.The_List, MTA); end loop; return List_MT; end Read_List; function Read_Form return Types.Mal_Type_Access is use Types; MT : Types.Mal_Type_Access; begin MT := Get_Token; if MT.all = (Sym_Type => Sym, Symbol => '(') then return Read_List; else return MT; end if; end Read_Form; function Read_Str (S : String) return Types.Mal_Type_Access is begin Analyzer.Reset; Input_Feeder.Set (S); return Read_Form; exception when OPENTOKEN.SYNTAX_ERROR => Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "Lexical error at char " & Integer'Image (Analyzer.Line)); raise Ada.IO_Exceptions.End_Error; end Read_Str; end Reader;
with Ada.IO_Exceptions; with Ada.Characters.Latin_1; with Ada.Strings.Maps.Constants; with Ada.Strings.Unbounded; with Ada.Text_IO; with Opentoken.Recognizer.Character_Set; with Opentoken.Recognizer.Identifier; with Opentoken.Recognizer.Integer; with Opentoken.Recognizer.Keyword; with Opentoken.Recognizer.Line_Comment; with Opentoken.Recognizer.Separator; with Opentoken.Recognizer.Single_Character_Set; with Opentoken.Recognizer.String; with OpenToken.Text_Feeder.String; with Opentoken.Token.Enumerated.Analyzer; package body Reader is type Lexemes is (Int, Sym, Nil, True_Tok, False_Tok, Exp_Tok, Str, Atom, Whitespace, Comment); package Lisp_Tokens is new Opentoken.Token.Enumerated (Lexemes); package Tokenizer is new Lisp_Tokens.Analyzer; Exp_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Separator.Get ("**")); Nil_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("nil")); True_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Keyword.Get ("true")); False_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Keyword.Get ("false")); ID_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Identifier.Get); Int_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Integer.Get); -- Use the C style for escaped strings. String_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.String.Get (Escapeable => True, Double_Delimiter => False)); -- Atom definition Start_Chars : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.Constants.Letter_Set; Body_Chars : Ada.Strings.Maps.Character_Set := Ada.Strings.Maps."or" (Ada.Strings.Maps.Constants.Alphanumeric_Set, Ada.Strings.Maps.To_Set ('-')); Atom_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Identifier.Get (Start_Chars, Body_Chars)); Lisp_Syms : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set ("[]{}()'`~^@+-*/"); Sym_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Single_Character_Set.Get (Lisp_Syms)); Lisp_Whitespace : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set (Ada.Characters.Latin_1.HT & Ada.Characters.Latin_1.Space & Ada.Characters.Latin_1.Comma); Whitesp_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get (Opentoken.Recognizer.Character_Set.Get (Lisp_Whitespace)); Comment_Recognizer : constant Tokenizer.Recognizable_Token := Tokenizer.Get(Opentoken.Recognizer.Line_Comment.Get (";")); Syntax : constant Tokenizer.Syntax := (Int => Int_Recognizer, Sym => Sym_Recognizer, Nil => Nil_Recognizer, True_Tok => True_Recognizer, False_Tok => False_Recognizer, Exp_Tok => Exp_Recognizer, Str => String_Recognizer, Atom => Atom_Recognizer, Whitespace => Whitesp_Recognizer, Comment => Comment_Recognizer --, ); Input_Feeder : aliased OpenToken.Text_Feeder.String.Instance; Analyzer : Tokenizer.Instance := Tokenizer.Initialize (Syntax, Input_Feeder'access); function Get_Token_String return String is begin return Tokenizer.Lexeme (Analyzer); end Get_Token_String; function Get_Token_Char return Character is S : String := Tokenizer.Lexeme (Analyzer); begin return S(S'First); end Get_Token_Char; function Get_Token return Types.Mal_Type_Access is Res : Types.Mal_Type_Access; begin Tokenizer.Find_Next (Analyzer); case Tokenizer.ID (Analyzer) is when Int => Res := new Types.Mal_Type' (Sym_Type => Types.Int, Int_Val => Integer'Value (Get_Token_String)); when Sym => Res := new Types.Mal_Type' (Sym_Type => Types.Sym, Symbol => Get_Token_Char); when Nil => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when True_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when False_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Exp_Tok => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Str => Res := new Types.Mal_Type' (Sym_Type => Types.Str, The_String => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Atom => Res := new Types.Mal_Type' (Sym_Type => Types.Atom, The_Atom => Ada.Strings.Unbounded.To_Unbounded_String (Get_Token_String)); when Whitespace | Comment => null; end case; return Res; end Get_Token; -- Parsing function Read_Form return Types.Mal_Type_Access; function Read_List return Types.Mal_Type_Access is use types; List_MT, MTA : Types.Mal_Type_Access; begin List_MT := new Types.Mal_Type' (Sym_Type => Types.List, The_List => Types.Lists.Empty_List); loop MTA := Read_Form; exit when MTA = null or else MTA.all = (Sym_Type => Sym, Symbol => ')'); Types.Lists.Append (List_MT.The_List, MTA); end loop; return List_MT; end Read_List; function Read_Form return Types.Mal_Type_Access is use Types; MT : Types.Mal_Type_Access; begin MT := Get_Token; if MT.all = (Sym_Type => Sym, Symbol => '(') then return Read_List; else return MT; end if; end Read_Form; function Read_Str (S : String) return Types.Mal_Type_Access is begin Analyzer.Reset; Input_Feeder.Set (S); return Read_Form; exception when OPENTOKEN.SYNTAX_ERROR => Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "Lexical error at char " & Integer'Image (Analyzer.Line)); raise Ada.IO_Exceptions.End_Error; end Read_Str; end Reader;
Fix escapable strings
Ada: Fix escapable strings
Ada
mpl-2.0
mpwillson/mal,0gajun/mal,DomBlack/mal,foresterre/mal,SawyerHood/mal,alantsev/mal,SawyerHood/mal,SawyerHood/mal,SawyerHood/mal,mpwillson/mal,alantsev/mal,DomBlack/mal,hterkelsen/mal,mpwillson/mal,foresterre/mal,hterkelsen/mal,DomBlack/mal,jwalsh/mal,joncol/mal,SawyerHood/mal,SawyerHood/mal,hterkelsen/mal,jwalsh/mal,jwalsh/mal,foresterre/mal,0gajun/mal,jwalsh/mal,SawyerHood/mal,0gajun/mal,foresterre/mal,alantsev/mal,alantsev/mal,hterkelsen/mal,DomBlack/mal,0gajun/mal,DomBlack/mal,hterkelsen/mal,joncol/mal,foresterre/mal,foresterre/mal,0gajun/mal,foresterre/mal,foresterre/mal,jwalsh/mal,DomBlack/mal,0gajun/mal,alantsev/mal,jwalsh/mal,jwalsh/mal,jwalsh/mal,jwalsh/mal,DomBlack/mal,foresterre/mal,foresterre/mal,SawyerHood/mal,SawyerHood/mal,hterkelsen/mal,DomBlack/mal,0gajun/mal,mpwillson/mal,jwalsh/mal,alantsev/mal,hterkelsen/mal,0gajun/mal,alantsev/mal,0gajun/mal,jwalsh/mal,alantsev/mal,DomBlack/mal,mpwillson/mal,hterkelsen/mal,mpwillson/mal,alantsev/mal,DomBlack/mal,foresterre/mal,0gajun/mal,hterkelsen/mal,alantsev/mal,SawyerHood/mal,SawyerHood/mal,mpwillson/mal,hterkelsen/mal,alantsev/mal,DomBlack/mal,0gajun/mal,foresterre/mal,hterkelsen/mal,SawyerHood/mal,DomBlack/mal,DomBlack/mal,mpwillson/mal,DomBlack/mal,SawyerHood/mal,joncol/mal,hterkelsen/mal,hterkelsen/mal,hterkelsen/mal,alantsev/mal,hterkelsen/mal,DomBlack/mal,foresterre/mal,hterkelsen/mal,mpwillson/mal,SawyerHood/mal,0gajun/mal,foresterre/mal,mpwillson/mal,hterkelsen/mal,mpwillson/mal,alantsev/mal,0gajun/mal,alantsev/mal,alantsev/mal,hterkelsen/mal,alantsev/mal,DomBlack/mal,foresterre/mal,0gajun/mal,DomBlack/mal,jwalsh/mal,foresterre/mal,jwalsh/mal,0gajun/mal,SawyerHood/mal,jwalsh/mal,0gajun/mal,mpwillson/mal,SawyerHood/mal,jwalsh/mal,0gajun/mal,mpwillson/mal,0gajun/mal,SawyerHood/mal,alantsev/mal,hterkelsen/mal,mpwillson/mal,jwalsh/mal,DomBlack/mal,SawyerHood/mal,0gajun/mal,foresterre/mal,DomBlack/mal,DomBlack/mal,0gajun/mal,DomBlack/mal,jwalsh/mal
f920090d150952b3ccf48d430f681b283ddaa72f
src/util-dates.ads
src/util-dates.ads
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Calendar.Arithmetic; with Ada.Calendar.Time_Zones; -- = Date Utilities = -- The `Util.Dates` package provides various date utilities to help in formatting and parsing -- dates in various standard formats. It completes the standard `Ada.Calendar.Formatting` and -- other packages by implementing specific formatting and parsing. -- -- == Date Operations == -- Several operations allow to compute from a given date: -- -- * `Get_Day_Start`: The start of the day (0:00), -- * `Get_Day_End`: The end of the day (23:59:59), -- * `Get_Week_Start`: The start of the week, -- * `Get_Week_End`: The end of the week, -- * `Get_Month_Start`: The start of the month, -- * `Get_Month_End`: The end of the month -- -- The `Date_Record` type represents a date in a split format allowing -- to access easily the day, month, hour and other information. -- -- Now : Ada.Calendar.Time := Ada.Calendar.Clock; -- Week_Start : Ada.Calendar.Time := Get_Week_Start (Now); -- Week_End : Ada.Calendar.Time := Get_Week_End (Now); -- -- @include util-dates-rfc7231.ads -- @include util-dates-iso8601.ads -- @include util-dates-formats.ads package Util.Dates is -- The Unix equivalent of 'struct tm'. type Date_Record is record Date : Ada.Calendar.Time; Year : Ada.Calendar.Year_Number := 1901; Month : Ada.Calendar.Month_Number := 1; Month_Day : Ada.Calendar.Day_Number := 1; Day : Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Tuesday; Hour : Ada.Calendar.Formatting.Hour_Number := 0; Minute : Ada.Calendar.Formatting.Minute_Number := 0; Second : Ada.Calendar.Formatting.Second_Number := 0; Sub_Second : Ada.Calendar.Formatting.Second_Duration := 0.0; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset := 0; Leap_Second : Boolean := False; end record; -- Split the date into a date record (See Ada.Calendar.Formatting.Split). procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0); -- Return the date from the date record (See Ada.Calendar.Formatting.Time_Of). function Time_Of (Date : in Date_Record) return Ada.Calendar.Time; -- Returns true if the given year is a leap year. function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean; -- Get the number of days in the given year. function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get the number of days in the given month. function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get a time representing the given date at 00:00:00. function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the given date at 23:59:59. function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the week at 00:00:00. function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the week at 23:59:99. function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the month at 00:00:00. function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the month at 23:59:59. function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; end Util.Dates;
----------------------------------------------------------------------- -- util-dates -- Date utilities -- Copyright (C) 2011, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Calendar.Arithmetic; with Ada.Calendar.Time_Zones; -- = Date Utilities = -- The `Util.Dates` package provides various date utilities to help in formatting and parsing -- dates in various standard formats. It completes the standard `Ada.Calendar.Formatting` and -- other packages by implementing specific formatting and parsing. -- -- == Date Operations == -- Several operations allow to compute from a given date: -- -- * `Get_Day_Start`: The start of the day (0:00), -- * `Get_Day_End`: The end of the day (23:59:59), -- * `Get_Week_Start`: The start of the week, -- * `Get_Week_End`: The end of the week, -- * `Get_Month_Start`: The start of the month, -- * `Get_Month_End`: The end of the month -- -- The `Date_Record` type represents a date in a split format allowing -- to access easily the day, month, hour and other information. -- -- Now : Ada.Calendar.Time := Ada.Calendar.Clock; -- Week_Start : Ada.Calendar.Time := Get_Week_Start (Now); -- Week_End : Ada.Calendar.Time := Get_Week_End (Now); -- -- @include util-dates-rfc7231.ads -- @include util-dates-iso8601.ads -- @include util-dates-formats.ads package Util.Dates is -- The Unix equivalent of 'struct tm'. type Date_Record is record Date : Ada.Calendar.Time; Year : Ada.Calendar.Year_Number := 1901; Month : Ada.Calendar.Month_Number := 1; Month_Day : Ada.Calendar.Day_Number := 1; Day : Ada.Calendar.Formatting.Day_Name := Ada.Calendar.Formatting.Tuesday; Hour : Ada.Calendar.Formatting.Hour_Number := 0; Minute : Ada.Calendar.Formatting.Minute_Number := 0; Second : Ada.Calendar.Formatting.Second_Number := 0; Sub_Second : Ada.Calendar.Formatting.Second_Duration := 0.0; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset := 0; Leap_Second : Boolean := False; end record; -- Split the date into a date record (See Ada.Calendar.Formatting.Split). procedure Split (Into : out Date_Record; Date : in Ada.Calendar.Time; Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0); -- Return the date from the date record (See Ada.Calendar.Formatting.Time_Of). function Time_Of (Date : in Date_Record) return Ada.Calendar.Time; -- Returns true if the given year is a leap year. function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean; -- Returns true if both dates are on the same day. function Is_Same_Day (Date1, Date2 : in Ada.Calendar.Time) return Boolean; function Is_Same_Day (Date1, Date2 : in Date_Record) return Boolean; -- Get the number of days in the given year. function Get_Day_Count (Year : in Ada.Calendar.Year_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get the number of days in the given month. function Get_Day_Count (Year : in Ada.Calendar.Year_Number; Month : in Ada.Calendar.Month_Number) return Ada.Calendar.Arithmetic.Day_Count; -- Get a time representing the given date at 00:00:00. function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the given date at 23:59:59. function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the week at 00:00:00. function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the week at 23:59:99. function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the beginning of the month at 00:00:00. function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; -- Get a time representing the end of the month at 23:59:59. function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time; function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time; end Util.Dates;
Declare the Is_Same_Day function to check if two times are on the same day
Declare the Is_Same_Day function to check if two times are on the same day
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b1c34407db344d0a3ef2a9ae428bce7302945139
awa/src/awa-permissions-beans.adb
awa/src/awa-permissions-beans.adb
----------------------------------------------------------------------- -- awa-permissions-beans -- Permission beans -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Events.Action_Method; with AWA.Permissions.Services; package body AWA.Permissions.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; package Create_Binding is new AWA.Events.Action_Method.Bind (Bean => Permission_Bean, Method => Create, Name => "create"); Permission_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Binding.Proxy'Access); -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Permission_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_id" then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_type" then From.Kind := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Permission_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Permission_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new permission. -- ------------------------------ procedure Create (Bean : in out Permission_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; begin Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, To_String (Bean.Kind)); AWA.Permissions.Services.Add_Permission (Session => DB, Entity => Bean.Get_Entity_Id, Kind => Kind, User => Ctx.Get_User_Identifier); Ctx.Commit; end Create; -- ------------------------------ -- Create the permission bean instance. -- ------------------------------ function Create_Permission_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Permission_Bean; end Create_Permission_Bean; end AWA.Permissions.Beans;
----------------------------------------------------------------------- -- awa-permissions-beans -- Permission beans -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Events.Action_Method; with AWA.Permissions.Services; package body AWA.Permissions.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; package Create_Binding is new AWA.Events.Action_Method.Bind (Bean => Permission_Bean, Method => Create, Name => "create"); Permission_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Binding.Proxy'Access); -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Permission_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_id" then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_type" then From.Kind := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "workspace_id" then From.Set_Workspace_Id (ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Permission_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Permission_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new permission. -- ------------------------------ procedure Create (Bean : in out Permission_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; begin Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, To_String (Bean.Kind)); AWA.Permissions.Services.Add_Permission (Session => DB, Entity => Bean.Get_Entity_Id, Kind => Kind, User => Ctx.Get_User_Identifier, Workspace => Bean.Get_Workspace_Id); Ctx.Commit; end Create; -- ------------------------------ -- Create the permission bean instance. -- ------------------------------ function Create_Permission_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Permission_Bean; end Create_Permission_Bean; end AWA.Permissions.Beans;
Update the permission bean to add the workspace_id attribute and make the permission with it
Update the permission bean to add the workspace_id attribute and make the permission with it
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b0bffcee71907acb1ec64fa0ea9e8357799349db
src/util-beans-basic-lists.ads
src/util-beans-basic-lists.ads
----------------------------------------------------------------------- -- Util.Beans.Basic.Lists -- List bean given access to a vector -- 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 Ada.Containers; with Ada.Containers.Vectors; with Util.Beans.Objects; -- The <b>Util.Beans.Basic.Lists</b> generic package implements a list of -- elements that can be accessed through the <b>List_Bean</b> interface. generic type Element_Type is new Util.Beans.Basic.Readonly_Bean with private; package Util.Beans.Basic.Lists is -- Package that represents the vectors of elements. -- (gcc 4.4 crashes if this package is defined as generic parameter. package Vectors is new Ada.Containers.Vectors (Element_Type => Element_Type, Index_Type => Natural); -- The list of elements is defined in a public part so that applications -- can easily add or remove elements in the target list. The <b>List_Bean</b> -- type holds the real implementation with the private parts. type Abstract_List_Bean is abstract new Ada.Finalization.Controlled and Util.Beans.Basic.List_Bean with record List : Vectors.Vector; end record; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> type gives access to a list of objects. type List_Bean is new Abstract_List_Bean with private; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Bean) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Bean; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Initialize the list bean. overriding procedure Initialize (Object : in out List_Bean); -- Deletes the list bean procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access); private type List_Bean is new Abstract_List_Bean with record Current : aliased Element_Type; Row : Util.Beans.Objects.Object; end record; end Util.Beans.Basic.Lists;
----------------------------------------------------------------------- -- Util.Beans.Basic.Lists -- List bean given access to a vector -- 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.Finalization; with Ada.Containers; with Ada.Containers.Vectors; with Util.Beans.Objects; -- The <b>Util.Beans.Basic.Lists</b> generic package implements a list of -- elements that can be accessed through the <b>List_Bean</b> interface. generic type Element_Type is new Util.Beans.Basic.Readonly_Bean with private; package Util.Beans.Basic.Lists is -- Package that represents the vectors of elements. -- (gcc 4.4 crashes if this package is defined as generic parameter. package Vectors is new Ada.Containers.Vectors (Element_Type => Element_Type, Index_Type => Natural); -- The list of elements is defined in a public part so that applications -- can easily add or remove elements in the target list. The <b>List_Bean</b> -- type holds the real implementation with the private parts. type Abstract_List_Bean is abstract new Ada.Finalization.Controlled and Util.Beans.Basic.List_Bean with record List : aliased Vectors.Vector; end record; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> type gives access to a list of objects. type List_Bean is new Abstract_List_Bean with private; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Bean) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Bean; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Initialize the list bean. overriding procedure Initialize (Object : in out List_Bean); -- Deletes the list bean procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access); private type List_Bean is new Abstract_List_Bean with record Current : aliased Element_Type; Row : Util.Beans.Objects.Object; end record; end Util.Beans.Basic.Lists;
Make the List an aliased member to help the Rest operations
Make the List an aliased member to help the Rest operations
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
861ffca60ad867890ee33f43058ae68eb1621790
src/util-concurrent-copies.adb
src/util-concurrent-copies.adb
----------------------------------------------------------------------- -- Util.Concurrent.Copies -- Concurrent Tools -- 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 Util.Concurrent.Copies is protected body Atomic is -- ------------------------------ -- Get the value atomically -- ------------------------------ function Get return Element_Type is begin return Value; end Get; -- ------------------------------ -- Change the value atomically. -- ------------------------------ procedure Set (Object : in Element_Type) is begin Value := Object; end Set; end Atomic; end Util.Concurrent.Copies;
----------------------------------------------------------------------- -- util-concurrent-copies -- Concurrent Tools -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Concurrent.Copies is protected body Atomic is -- ------------------------------ -- Get the value atomically -- ------------------------------ function Get return Element_Type is begin return Value; end Get; -- ------------------------------ -- Change the value atomically. -- ------------------------------ procedure Set (Object : in Element_Type) is begin Value := Object; end Set; end Atomic; end Util.Concurrent.Copies;
Update the header
Update the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d72c9104f181059a2595de0aeef0f80588f214c8
src/babel-files-maps.ads
src/babel-files-maps.ads
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- 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.Hashed_Maps; with Util.Strings; package Babel.Files.Maps is -- Babel.Base.Get_File_Map (Directory, File_Map); -- Babel.Base.Get_Directory_Map (Directory, Dir_Map); -- File_Map.Find (New_File); -- Dir_Map.Find (New_File); -- Hash string -> File package File_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => File_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype File_Map is File_Maps.Map; subtype File_Cursor is File_Maps.Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Type; -- Hash string -> Directory package Directory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => Directory_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype Directory_Map is Directory_Maps.Map; subtype Directory_Cursor is Directory_Maps.Cursor; type Differential_Container is new Babel.Files.Default_Container with private; -- Add the file with the given name in the container. overriding procedure Add_File (Into : in out Differential_Container; Element : in File_Type); -- Add the directory with the given name in the container. overriding procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. overriding function Find (From : in Differential_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. overriding function Find (From : in Differential_Container; Name : in String) return Directory_Type; -- Set the directory object associated with the container. overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type); -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)); private type Differential_Container is new Babel.Files.Default_Container with record Known_Files : File_Map; Known_Dirs : Directory_Map; end record; end Babel.Files.Maps;
----------------------------------------------------------------------- -- babel-files-maps -- Hash maps for files and directories -- 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.Hashed_Maps; with Util.Strings; package Babel.Files.Maps is -- Babel.Base.Get_File_Map (Directory, File_Map); -- Babel.Base.Get_Directory_Map (Directory, Dir_Map); -- File_Map.Find (New_File); -- Dir_Map.Find (New_File); -- Hash string -> File package File_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => File_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype File_Map is File_Maps.Map; subtype File_Cursor is File_Maps.Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Cursor; -- Find the file with the given name in the file map. function Find (From : in File_Map; Name : in String) return File_Type; -- Hash string -> Directory package Directory_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => Directory_Type, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings."=", "=" => "="); subtype Directory_Map is Directory_Maps.Map; subtype Directory_Cursor is Directory_Maps.Cursor; -- Find the directory with the given name in the directory map. function Find (From : in Directory_Map; Name : in String) return Directory_Cursor; -- Find the directory with the given name in the directory map. function Find (From : in Directory_Map; Name : in String) return Directory_Type; type Differential_Container is new Babel.Files.Default_Container with private; -- Add the file with the given name in the container. overriding procedure Add_File (Into : in out Differential_Container; Element : in File_Type); -- Add the directory with the given name in the container. overriding procedure Add_Directory (Into : in out Differential_Container; Element : in Directory_Type); -- Create a new file instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return File_Type; -- Create a new directory instance with the given name in the container. overriding function Create (Into : in Differential_Container; Name : in String) return Directory_Type; -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. overriding function Find (From : in Differential_Container; Name : in String) return File_Type; -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. overriding function Find (From : in Differential_Container; Name : in String) return Directory_Type; -- Set the directory object associated with the container. overriding procedure Set_Directory (Into : in out Differential_Container; Directory : in Directory_Type); -- Prepare the differential container by setting up the known files and known -- directories. The <tt>Update</tt> procedure is called to give access to the -- maps that can be updated. procedure Prepare (Container : in out Differential_Container; Update : access procedure (Files : in out File_Map; Dirs : in out Directory_Map)); private type Differential_Container is new Babel.Files.Default_Container with record Known_Files : File_Map; Known_Dirs : Directory_Map; end record; end Babel.Files.Maps;
Define the Find operation to find a directory by its name
Define the Find operation to find a directory by its name
Ada
apache-2.0
stcarrez/babel
ae2778035e9cdc2bf0b2fb95716727c7431b9112
samples/pschema.adb
samples/pschema.adb
----------------------------------------------------------------------- -- pschema - Print the database schema -- 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 ADO; with ADO.Schemas.Mysql; with ADO.Drivers; with ADO.Sessions; with ADO.Sessions.Factory; with ADO.Schemas; with Ada.Text_IO; with Util.Log.Loggers; procedure Pschema is use ADO; use Ada; use ADO.Schemas; Factory : ADO.Sessions.Factory.Session_Factory; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session; Driver : constant String := DB.Get_Connection.Get_Driver.Get_Driver_Name; Schema : ADO.Schemas.Schema_Definition; Iter : Table_Cursor; begin if Driver /= "mysql" then Ada.Text_IO.Put_Line ("Loading and printing the database schema is supported for MySQL"); return; end if; ADO.Schemas.Mysql.Load_Schema (DB.Get_Connection, Schema); -- Dump the database schema using SQL create table forms. Iter := Get_Tables (Schema); while Has_Element (Iter) loop declare Table : constant Table_Definition := Element (Iter); Table_Iter : Column_Cursor := Get_Columns (Table); begin Ada.Text_IO.Put_Line ("create table " & Get_Name (Table) & " ("); while Has_Element (Table_Iter) loop declare Col : constant Column_Definition := Element (Table_Iter); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Get_Name (Col)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Column_Type'Image (Get_Type (Col))); if not Is_Null (Col) then Ada.Text_IO.Put (" not null"); end if; Ada.Text_IO.Put_Line (","); end; Next (Table_Iter); end loop; Ada.Text_IO.Put_Line (");"); end; Next (Iter); end loop; end; end Pschema;
----------------------------------------------------------------------- -- pschema - Print the database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with ADO.Drivers; with ADO.Sessions; with ADO.Sessions.Factory; with ADO.Schemas; with Ada.Text_IO; with Util.Log.Loggers; procedure Pschema is use ADO; use Ada; use ADO.Schemas; Factory : ADO.Sessions.Factory.Session_Factory; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session; Schema : ADO.Schemas.Schema_Definition; Iter : Table_Cursor; begin DB.Load_Schema (Schema); -- Dump the database schema using SQL create table forms. Iter := Get_Tables (Schema); while Has_Element (Iter) loop declare Table : constant Table_Definition := Element (Iter); Table_Iter : Column_Cursor := Get_Columns (Table); begin Ada.Text_IO.Put_Line ("create table " & Get_Name (Table) & " ("); while Has_Element (Table_Iter) loop declare Col : constant Column_Definition := Element (Table_Iter); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Get_Name (Col)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Column_Type'Image (Get_Type (Col))); if not Is_Null (Col) then Ada.Text_IO.Put (" not null"); end if; Ada.Text_IO.Put_Line (","); end; Next (Table_Iter); end loop; Ada.Text_IO.Put_Line (");"); end; Next (Iter); end loop; end; end Pschema;
Update the example to use the Load_Schema procedure and be independent of the database
Update the example to use the Load_Schema procedure and be independent of the database
Ada
apache-2.0
stcarrez/ada-ado
8ef8a2c80289b355cfde58db065c41098ecc80bc
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
----------------------------------------------------------------------- -- awa-tags-modules-tests -- Unit tests for tags module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tags.Beans; package body AWA.Tags.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Tags.Modules"); function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag", Test_Add_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag", Test_Remove_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Update_Tags", Test_Remove_Tag'Access); end Add_Tests; function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access is Bean : constant Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module); begin return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Test tag creation. -- ------------------------------ procedure Test_Add_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); -- Create a tag. Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null"); end; end Test_Add_Tag; -- ------------------------------ -- Test tag removal. -- ------------------------------ procedure Test_Remove_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null"); end; end Test_Remove_Tag; -- ------------------------------ -- Test tag creation and removal. -- ------------------------------ procedure Test_Update_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; Tags : Util.Strings.Vectors.Vector; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); List.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("workspace-create"))); -- Add 3 tags. Tags.Append ("user-tag-1"); Tags.Append ("user-tag-2"); Tags.Append ("user-tag-3"); List.Set_Added (Tags); List.Update_Tags (User.Get_Id); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 3, Integer (List.Get_Count), "Invalid number of tags"); -- Remove a tag that was not created. Tags.Append ("user-tag-4"); List.Set_Deleted (Tags); Tags.Clear; Tags.Append ("user-tag-5"); List.Set_Added (Tags); List.Update_Tags (User.Get_Id); -- 'user-tag-5' is the only tag that should exist now. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null"); end; end Test_Update_Tag; end AWA.Tags.Modules.Tests;
----------------------------------------------------------------------- -- awa-tags-modules-tests -- Unit tests for tags module -- Copyright (C) 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tags.Beans; package body AWA.Tags.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Tags.Modules"); function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag", Test_Add_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag", Test_Remove_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Update_Tags", Test_Remove_Tag'Access); end Add_Tests; function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access is Bean : constant Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module); begin return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Test tag creation. -- ------------------------------ procedure Test_Add_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); -- Create a tag. Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null"); end; end Test_Add_Tag; -- ------------------------------ -- Test tag removal. -- ------------------------------ procedure Test_Remove_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null"); end; end Test_Remove_Tag; -- ------------------------------ -- Test tag creation and removal. -- ------------------------------ procedure Test_Update_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; Tags : Util.Strings.Vectors.Vector; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); List.Set_Value ("permission", Util.Beans.Objects.To_Object (String '("workspace-create"))); -- Add 3 tags. Tags.Append ("user-tag-1"); Tags.Append ("user-tag-2"); Tags.Append ("user-tag-3"); List.Set_Added (Tags); List.Update_Tags (User.Get_Id); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 3, Integer (List.Get_Count), "Invalid number of tags"); -- Remove a tag that was not created. Tags.Append ("user-tag-4"); List.Set_Deleted (Tags); Tags.Clear; Tags.Append ("user-tag-5"); List.Set_Added (Tags); List.Update_Tags (User.Get_Id); -- 'user-tag-5' is the only tag that should exist now. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null"); end; end Test_Update_Tag; end AWA.Tags.Modules.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7203c55f02454d890a85ec0aeebfe20baf69597f
src/babel-strategies.adb
src/babel-strategies.adb
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Babel.Files; with Babel.Files.Buffers; with Babel.Files.Lifecycles; with Babel.Stores; package body Babel.Strategies is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies"); -- ------------------------------ -- Allocate a buffer to read the file content. -- ------------------------------ function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is Result : Babel.Files.Buffers.Buffer_Access; begin Strategy.Buffers.Get_Buffer (Result); return Result; end Allocate_Buffer; -- ------------------------------ -- Release the buffer that was allocated by Allocate_Buffer. -- ------------------------------ procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access) is begin Babel.Files.Buffers.Release (Buffer); Buffer := null; end Release_Buffer; -- ------------------------------ -- 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) is begin Strategy.Buffers := Buffers; end Set_Buffers; -- 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) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Read_Store.Read (Path, Into.all); end Read_File; -- 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) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Write_Store.Write (Path, Content.all); end Write_File; -- 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) is begin Strategy.Database.Insert (File); if Strategy.Listeners /= null then if Babel.Files.Is_New (File) then Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File); else Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File); end if; end if; Strategy.Write_File (File, Content); Strategy.Release_Buffer (Content); end Backup_File; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is Path : constant String := Babel.Files.Get_Path (Directory); begin Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all); end Scan; -- ------------------------------ -- 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) is procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is begin Babel.Files.Queues.Add_Directory (Queue, Directory); end Append_Directory; Dir : Babel.Files.Directory_Type; begin while Babel.Files.Queues.Has_Directory (Queue) loop Babel.Files.Queues.Peek_Directory (Queue, Dir); Container.Set_Directory (Dir); Strategy_Type'Class (Strategy).Scan (Dir, Container); Container.Each_Directory (Append_Directory'Access); end loop; end Scan; -- ------------------------------ -- 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) is begin Strategy.Filters := Filters; end Set_Filters; -- ------------------------------ -- 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) is begin Strategy.Read_Store := Read; Strategy.Write_Store := Write; end Set_Stores; -- ------------------------------ -- Set the listeners to inform about changes. -- ------------------------------ procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List) is begin Strategy.Listeners := Listeners; end Set_Listeners; -- ------------------------------ -- Set the database for use by the strategy. -- ------------------------------ procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access) is begin -- Strategy.Database := Database; null; end Set_Database; end Babel.Strategies;
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Babel.Files; with Babel.Files.Buffers; with Babel.Files.Lifecycles; with Babel.Stores; package body Babel.Strategies is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies"); -- ------------------------------ -- Allocate a buffer to read the file content. -- ------------------------------ function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is Result : Babel.Files.Buffers.Buffer_Access; begin Strategy.Buffers.Get_Buffer (Result); return Result; end Allocate_Buffer; -- ------------------------------ -- Release the buffer that was allocated by Allocate_Buffer. -- ------------------------------ procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access) is begin Babel.Files.Buffers.Release (Buffer); Buffer := null; end Release_Buffer; -- ------------------------------ -- 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) is begin Strategy.Buffers := Buffers; end Set_Buffers; -- 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) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Read_Store.Read_File (Path, Stream); end Read_File; -- 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) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Write_Store.Write_File (Path, Stream, Babel.Files.Get_Mode (File)); end Write_File; -- 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) is begin Strategy.Database.Insert (File); if Strategy.Listeners /= null then if Babel.Files.Is_New (File) then Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File); else Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File); end if; end if; Strategy.Write_File (File, Stream); end Backup_File; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is Path : constant String := Babel.Files.Get_Path (Directory); begin Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all); end Scan; -- ------------------------------ -- 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) is procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is begin Babel.Files.Queues.Add_Directory (Queue, Directory); end Append_Directory; Dir : Babel.Files.Directory_Type; begin while Babel.Files.Queues.Has_Directory (Queue) loop Babel.Files.Queues.Peek_Directory (Queue, Dir); Container.Set_Directory (Dir); Strategy_Type'Class (Strategy).Scan (Dir, Container); Container.Each_Directory (Append_Directory'Access); end loop; end Scan; -- ------------------------------ -- 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) is begin Strategy.Filters := Filters; end Set_Filters; -- ------------------------------ -- 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) is begin Strategy.Read_Store := Read; Strategy.Write_Store := Write; end Set_Stores; -- ------------------------------ -- Set the listeners to inform about changes. -- ------------------------------ procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List) is begin Strategy.Listeners := Listeners; end Set_Listeners; -- ------------------------------ -- Set the database for use by the strategy. -- ------------------------------ procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access) is begin -- Strategy.Database := Database; null; end Set_Database; end Babel.Strategies;
Use the Babel.Streams.Refs.Stream_Ref type for Read_File and Write_File operations
Use the Babel.Streams.Refs.Stream_Ref type for Read_File and Write_File operations
Ada
apache-2.0
stcarrez/babel
31aa75a53e073875be026ef0579eee1859856056
src/babel-strategies.adb
src/babel-strategies.adb
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Babel.Files; with Babel.Files.Buffers; with Babel.Files.Lifecycles; with Babel.Stores; package body Babel.Strategies is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies"); -- ------------------------------ -- Allocate a buffer to read the file content. -- ------------------------------ function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is Result : Babel.Files.Buffers.Buffer_Access; begin Strategy.Buffers.Get_Instance (Result); return Result; end Allocate_Buffer; -- ------------------------------ -- Release the buffer that was allocated by Allocate_Buffer. -- ------------------------------ procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access) is begin Strategy.Buffers.Release (Buffer); Buffer := null; end Release_Buffer; -- ------------------------------ -- 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) is begin Strategy.Buffers := Buffers; end Set_Buffers; -- 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) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Read_Store.Read (Path, Into.all); end Read_File; -- 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) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Write_Store.Write (Path, Content.all); end Write_File; procedure Print_Sha (File : in Babel.Files.File_Type) is Sha : constant String := Babel.Files.Get_SHA1 (File); begin Log.Info (Babel.Files.Get_Path (File) & " => " & Sha); end Print_Sha; -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in out Babel.Files.Buffers.Buffer_Access) is begin if Babel.Files.Is_New (File) then Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File); else Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File); end if; Print_Sha (File); Strategy.Write_File (File, Content); Strategy.Release_Buffer (Content); end Backup_File; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is Path : constant String := Babel.Files.Get_Path (Directory); begin Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all); end Scan; -- ------------------------------ -- 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) is procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is begin Babel.Files.Queues.Add_Directory (Queue, Directory); end Append_Directory; Dir : Babel.Files.Directory_Type; begin while Babel.Files.Queues.Has_Directory (Queue) loop Babel.Files.Queues.Peek_Directory (Queue, Dir); Container.Set_Directory (Dir); Strategy_Type'Class (Strategy).Scan (Dir, Container); Container.Each_Directory (Append_Directory'Access); end loop; end Scan; -- ------------------------------ -- 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) is begin Strategy.Filters := Filters; end Set_Filters; -- ------------------------------ -- 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) is begin Strategy.Read_Store := Read; Strategy.Write_Store := Write; end Set_Stores; -- ------------------------------ -- Set the listeners to inform about changes. -- ------------------------------ procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List) is begin Strategy.Listeners := Listeners; end Set_Listeners; end Babel.Strategies;
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Babel.Files; with Babel.Files.Buffers; with Babel.Files.Lifecycles; with Babel.Stores; package body Babel.Strategies is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies"); -- ------------------------------ -- Allocate a buffer to read the file content. -- ------------------------------ function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access is Result : Babel.Files.Buffers.Buffer_Access; begin Strategy.Buffers.Get_Instance (Result); return Result; end Allocate_Buffer; -- ------------------------------ -- Release the buffer that was allocated by Allocate_Buffer. -- ------------------------------ procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access) is begin Strategy.Buffers.Release (Buffer); Buffer := null; end Release_Buffer; -- ------------------------------ -- 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) is begin Strategy.Buffers := Buffers; end Set_Buffers; -- 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) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Read_Store.Read (Path, Into.all); end Read_File; -- 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) is Path : constant String := Babel.Files.Get_Path (File); begin Strategy.Write_Store.Write (Path, Content.all); end Write_File; procedure Print_Sha (File : in Babel.Files.File_Type) is Sha : constant String := Babel.Files.Get_SHA1 (File); begin Log.Info (Babel.Files.Get_Path (File) & " => " & Sha); end Print_Sha; -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in out Babel.Files.Buffers.Buffer_Access) is begin if Babel.Files.Is_New (File) then Babel.Files.Lifecycles.Notify_Create (Strategy.Listeners.all, File); else Babel.Files.Lifecycles.Notify_Update (Strategy.Listeners.all, File); end if; Print_Sha (File); Strategy.Write_File (File, Content); Strategy.Release_Buffer (Content); end Backup_File; -- Scan the directory procedure Scan (Strategy : in out Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is Path : constant String := Babel.Files.Get_Path (Directory); begin Strategy.Read_Store.Scan (Path, Container, Strategy.Filters.all); end Scan; -- ------------------------------ -- 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) is procedure Append_Directory (Directory : in Babel.Files.Directory_Type) is begin Babel.Files.Queues.Add_Directory (Queue, Directory); end Append_Directory; Dir : Babel.Files.Directory_Type; begin while Babel.Files.Queues.Has_Directory (Queue) loop Babel.Files.Queues.Peek_Directory (Queue, Dir); Container.Set_Directory (Dir); Strategy_Type'Class (Strategy).Scan (Dir, Container); Container.Each_Directory (Append_Directory'Access); end loop; end Scan; -- ------------------------------ -- 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) is begin Strategy.Filters := Filters; end Set_Filters; -- ------------------------------ -- 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) is begin Strategy.Read_Store := Read; Strategy.Write_Store := Write; end Set_Stores; -- ------------------------------ -- Set the listeners to inform about changes. -- ------------------------------ procedure Set_Listeners (Strategy : in out Strategy_Type; Listeners : access Util.Listeners.List) is begin Strategy.Listeners := Listeners; end Set_Listeners; -- ------------------------------ -- Set the database for use by the strategy. -- ------------------------------ procedure Set_Database (Strategy : in out Strategy_Type; Database : in Babel.Base.Database_Access) is begin Strategy.Database := Database; end Set_Database; end Babel.Strategies;
Define the Set_Database operation
Define the Set_Database operation
Ada
apache-2.0
stcarrez/babel
25981b1a3ac00e5ed95e68a86fadd561e4a60f0b
regtests/util-locales-tests.adb
regtests/util-locales-tests.adb
----------------------------------------------------------------------- -- locales.tests -- Unit tests for locales -- 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; package body Util.Locales.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Locales.Get_Locale", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Language", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Country", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Variant", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Hash", Test_Hash_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.=", Test_Compare_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Locales", Test_Get_Locales'Access); end Add_Tests; procedure Test_Get_Locale (T : in out Test) is Loc : Locale; begin Loc := Get_Locale ("en"); Assert_Equals (T, "en", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant"); Loc := Get_Locale ("ja", "JP", "JP"); Assert_Equals (T, "ja", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "JP", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "JP", Get_Variant (Loc), "Invalid variant"); Loc := Get_Locale ("no", "NO", "NY"); Assert_Equals (T, "no", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "NO", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "NY", Get_Variant (Loc), "Invalid variant"); end Test_Get_Locale; procedure Test_Hash_Locale (T : in out Test) is use type Ada.Containers.Hash_Type; begin T.Assert (Hash (FRANCE) /= Hash (FRENCH), "Hash should be different"); T.Assert (Hash (FRANCE) /= Hash (ENGLISH), "Hash should be different"); T.Assert (Hash (FRENCH) /= Hash (ENGLISH), "Hash should be different"); end Test_Hash_Locale; procedure Test_Compare_Locale (T : in out Test) is begin T.Assert (FRANCE /= FRENCH, "Equality"); T.Assert (FRANCE = FRANCE, "Equality"); T.Assert (FRANCE = Get_Locale ("fr", "FR"), "Equality"); T.Assert (FRANCE /= ENGLISH, "Equality"); T.Assert (FRENCH /= ENGLISH, "Equaliy"); end Test_Compare_Locale; procedure Test_Get_Locales (T : in out Test) is begin for I in Locales'Range loop declare Language : constant String := Get_Language (Locales (I)); Country : constant String := Get_Country (Locales (I)); Variant : constant String := Get_Variant (Locales (I)); Loc : constant Locale := Get_Locale (Language, Country, Variant); Name : constant String := To_String (Loc); begin T.Assert (Loc = Locales (I), "Invalid locale at " & Positive'Image (I) & " " & Loc.all); if Variant'Length > 0 then Assert (T, Name, Language & "_" & Country & "_" & Variant, "Invalid To_String"); elsif Country'Length > 0 then Assert (T, Name, Language & "_" & Country, "Invalid To_String"); else Assert (T, Name, Language, "Invalid To_String"); end if; end; end loop; end Test_Get_Locales; end Util.Locales.Tests;
----------------------------------------------------------------------- -- locales.tests -- Unit tests for locales -- 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; package body Util.Locales.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Locales.Get_Locale", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Language", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Country", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Variant", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Hash", Test_Hash_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.=", Test_Compare_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Locales", Test_Get_Locales'Access); end Add_Tests; procedure Test_Get_Locale (T : in out Test) is Loc : Locale; begin Loc := Get_Locale ("en"); Assert_Equals (T, "en", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant"); Loc := Get_Locale ("ja", "JP", "JP"); Assert_Equals (T, "ja", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "JP", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "JP", Get_Variant (Loc), "Invalid variant"); Loc := Get_Locale ("no", "NO", "NY"); Assert_Equals (T, "no", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "NO", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "NY", Get_Variant (Loc), "Invalid variant"); end Test_Get_Locale; procedure Test_Hash_Locale (T : in out Test) is use type Ada.Containers.Hash_Type; begin T.Assert (Hash (FRANCE) /= Hash (FRENCH), "Hash should be different"); T.Assert (Hash (FRANCE) /= Hash (ENGLISH), "Hash should be different"); T.Assert (Hash (FRENCH) /= Hash (ENGLISH), "Hash should be different"); end Test_Hash_Locale; procedure Test_Compare_Locale (T : in out Test) is begin T.Assert (FRANCE /= FRENCH, "Equality"); T.Assert (FRANCE = FRANCE, "Equality"); T.Assert (FRANCE = Get_Locale ("fr", "FR"), "Equality"); T.Assert (FRANCE /= ENGLISH, "Equality"); T.Assert (FRENCH /= ENGLISH, "Equaliy"); end Test_Compare_Locale; procedure Test_Get_Locales (T : in out Test) is begin for I in Locales'Range loop declare Language : constant String := Get_Language (Locales (I)); Country : constant String := Get_Country (Locales (I)); Variant : constant String := Get_Variant (Locales (I)); Loc : constant Locale := Get_Locale (Language, Country, Variant); Name : constant String := To_String (Loc); begin T.Assert (Loc = Locales (I), "Invalid locale at " & Positive'Image (I) & " " & Loc.all); if Variant'Length > 0 then Assert_Equals (T, Name, Language & "_" & Country & "_" & Variant, "Invalid To_String"); elsif Country'Length > 0 then Assert_Equals (T, Name, Language & "_" & Country, "Invalid To_String"); else Assert_Equals (T, Name, Language, "Invalid To_String"); end if; end; end loop; end Test_Get_Locales; end Util.Locales.Tests;
Fix compilation with GNAT 2011
Fix compilation with GNAT 2011
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
32f18c644e98517656ea4bcdbab08c4839de945a
src/natools-s_expressions-generic_caches.ads
src/natools-s_expressions-generic_caches.ads
------------------------------------------------------------------------------ -- Copyright (c) 2013-2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.S_Expressions.Generic_Caches provides a simple memory container -- -- for S-expressions. The container is append-only, and provides cursors to -- -- replay it from start. -- -- This is a generic package that allow client-selected storage pools. An -- -- instance with default storage pools is provided in -- -- Natools.S_Expressions.Caches. -- -- The intended usage is efficient caching of S-expressions in memory. For -- -- more flexible in-memory S-expression objects, -- -- see Natools.S_Expressions.Holders. -- ------------------------------------------------------------------------------ with System.Storage_Pools; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Printers; with Natools.S_Expressions.Replayable; private with Ada.Finalization; private with Ada.Unchecked_Deallocation; private with Natools.References; generic Atom_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; Counter_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; Structure_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; package Natools.S_Expressions.Generic_Caches is pragma Preelaborate (Generic_Caches); type Reference is new Printers.Printer with private; pragma Preelaborable_Initialization (Reference); overriding procedure Open_List (Output : in out Reference); overriding procedure Append_Atom (Output : in out Reference; Data : in Atom); overriding procedure Close_List (Output : in out Reference); function Duplicate (Cache : Reference) return Reference; -- Create a new copy of the S-expression held in Cache and return it function Move (Source : in out S_Expressions.Descriptor'Class) return Reference; -- Build a new cache by (destructively) reading Original type Cursor is new Lockable.Descriptor and Replayable.Descriptor with private; pragma Preelaborable_Initialization (Cursor); overriding function Current_Event (Object : in Cursor) return Events.Event; overriding function Current_Atom (Object : in Cursor) return Atom; overriding function Current_Level (Object : in Cursor) return Natural; overriding procedure Query_Atom (Object : in Cursor; Process : not null access procedure (Data : in Atom)); overriding procedure Read_Atom (Object : in Cursor; Data : out Atom; Length : out Count); overriding procedure Next (Object : in out Cursor; Event : out Events.Event); overriding procedure Lock (Object : in out Cursor; State : out Lockable.Lock_State); overriding procedure Unlock (Object : in out Cursor; State : in out Lockable.Lock_State; Finish : in Boolean := True); overriding function Duplicate (Object : Cursor) return Cursor; function First (Cache : Reference'Class) return Cursor; -- Create a new Cursor pointing at the beginning of Cache function Move (Source : in out S_Expressions.Descriptor'Class) return Cursor is (Move (Source).First); -- Return a cursor holding a copy of Original (which is -- destructively read) private type Atom_Access is access Atom; for Atom_Access'Storage_Pool use Atom_Pool; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Atom, Atom_Access); type Node; type Node_Access is access Node; for Node_Access'Storage_Pool use Structure_Pool; type Node_Kind is (Atom_Node, List_Node); type Node (Kind : Node_Kind) is record Parent : Node_Access; Next : Node_Access; case Kind is when Atom_Node => Data : Atom_Access; when List_Node => Child : Node_Access; end case; end record; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Node, Node_Access); type Tree is new Ada.Finalization.Limited_Controlled with record Root : Node_Access := null; Last : Node_Access := null; Opening : Boolean := False; end record; procedure Append (Exp : in out Tree; Kind : in Node_Kind; Data : in Atom_Access := null); -- Append a new node of the given Kind to Exp procedure Close_List (Exp : in out Tree); -- Close innermost list function Create_Tree return Tree; -- Create a new empty Tree function Duplicate (Source : Tree) return Tree; -- Deep copy of a Tree object overriding procedure Finalize (Object : in out Tree); -- Release all nodes contained in Object package Trees is new References (Tree, Structure_Pool, Counter_Pool); type Reference is new Printers.Printer with record Exp : Trees.Reference; end record; type Cursor is new Lockable.Descriptor and Replayable.Descriptor with record Exp : Trees.Reference; Position : Node_Access := null; Opening : Boolean := False; Stack : Lockable.Lock_Stack; Locked : Boolean := False; end record; function Absolute_Level (Object : Cursor) return Natural; end Natools.S_Expressions.Generic_Caches;
------------------------------------------------------------------------------ -- Copyright (c) 2013-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.S_Expressions.Generic_Caches provides a simple memory container -- -- for S-expressions. The container is append-only, and provides cursors to -- -- replay it from start. -- -- This is a generic package that allow client-selected storage pools. An -- -- instance with default storage pools is provided in -- -- Natools.S_Expressions.Caches. -- -- The intended usage is efficient caching of S-expressions in memory. For -- -- more flexible in-memory S-expression objects, -- -- see Natools.S_Expressions.Holders. -- ------------------------------------------------------------------------------ with System.Storage_Pools; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Printers; with Natools.S_Expressions.Replayable; private with Ada.Finalization; private with Ada.Unchecked_Deallocation; private with Natools.References; generic Atom_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; Counter_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; Structure_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; package Natools.S_Expressions.Generic_Caches is pragma Preelaborate (Generic_Caches); type Reference is new Printers.Printer with private; pragma Preelaborable_Initialization (Reference); overriding procedure Open_List (Output : in out Reference); overriding procedure Append_Atom (Output : in out Reference; Data : in Atom); overriding procedure Close_List (Output : in out Reference); function Duplicate (Cache : Reference) return Reference; -- Create a new copy of the S-expression held in Cache and return it function Move (Source : in out S_Expressions.Descriptor'Class) return Reference; -- Build a new cache by (destructively) reading Original type Cursor is new Lockable.Descriptor and Replayable.Descriptor with private; pragma Preelaborable_Initialization (Cursor); overriding function Current_Event (Object : in Cursor) return Events.Event; overriding function Current_Atom (Object : in Cursor) return Atom; overriding function Current_Level (Object : in Cursor) return Natural; overriding procedure Query_Atom (Object : in Cursor; Process : not null access procedure (Data : in Atom)); overriding procedure Read_Atom (Object : in Cursor; Data : out Atom; Length : out Count); overriding procedure Next (Object : in out Cursor; Event : out Events.Event); overriding procedure Lock (Object : in out Cursor; State : out Lockable.Lock_State); overriding procedure Unlock (Object : in out Cursor; State : in out Lockable.Lock_State; Finish : in Boolean := True); overriding function Duplicate (Object : Cursor) return Cursor; function First (Cache : Reference'Class) return Cursor; -- Create a new Cursor pointing at the beginning of Cache function Move (Source : in out S_Expressions.Descriptor'Class) return Cursor is (Move (Source).First); -- Return a cursor holding a copy of Original (which is -- destructively read) function Conditional_Move (Source : in out S_Expressions.Descriptor'Class) return Cursor is (if Source in Cursor then Cursor (Source) else Move (Source).First); -- Return a copy of Source, with cheap copy if possible, -- otherwise with destructive Move private type Atom_Access is access Atom; for Atom_Access'Storage_Pool use Atom_Pool; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Atom, Atom_Access); type Node; type Node_Access is access Node; for Node_Access'Storage_Pool use Structure_Pool; type Node_Kind is (Atom_Node, List_Node); type Node (Kind : Node_Kind) is record Parent : Node_Access; Next : Node_Access; case Kind is when Atom_Node => Data : Atom_Access; when List_Node => Child : Node_Access; end case; end record; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Node, Node_Access); type Tree is new Ada.Finalization.Limited_Controlled with record Root : Node_Access := null; Last : Node_Access := null; Opening : Boolean := False; end record; procedure Append (Exp : in out Tree; Kind : in Node_Kind; Data : in Atom_Access := null); -- Append a new node of the given Kind to Exp procedure Close_List (Exp : in out Tree); -- Close innermost list function Create_Tree return Tree; -- Create a new empty Tree function Duplicate (Source : Tree) return Tree; -- Deep copy of a Tree object overriding procedure Finalize (Object : in out Tree); -- Release all nodes contained in Object package Trees is new References (Tree, Structure_Pool, Counter_Pool); type Reference is new Printers.Printer with record Exp : Trees.Reference; end record; type Cursor is new Lockable.Descriptor and Replayable.Descriptor with record Exp : Trees.Reference; Position : Node_Access := null; Opening : Boolean := False; Stack : Lockable.Lock_Stack; Locked : Boolean := False; end record; function Absolute_Level (Object : Cursor) return Natural; end Natools.S_Expressions.Generic_Caches;
add a cheaper-when-possible alternative to Move
s_expressions-generic_caches: add a cheaper-when-possible alternative to Move
Ada
isc
faelys/natools
62447487c090df30d1956191f43a93ff256341e8
matp/src/events/mat-events-probes.adb
matp/src/events/mat-events-probes.adb
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Events.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes"); procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; Manager.Frames := MAT.Frames.Create_Root; end Initialize; -- ------------------------------ -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Probe_Handler; begin Handler.Probe := Probe; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Probes.Insert (Name, Handler); end Register_Probe; -- ------------------------------ -- Get the target events. -- ------------------------------ function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access is begin return Client.Events; end Get_Target_Events; procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Tick_Ref; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : constant access MAT.Events.Frame_Info := Client.Frame; begin Client.Event.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_THREAD_ID => Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_FRAME_PC => for I in 1 .. Count loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); end if; end loop; when others => null; end case; end; end loop; -- Convert the time in usec to make computation easier. Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000; Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec); Frame.Cur_Depth := Count; exception when E : others => Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count)); raise; end Read_Probe; procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is use type MAT.Events.Attribute_Table_Ptr; use type MAT.Events.Targets.Target_Events_Access; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); end if; if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Probe_Handler := Handler_Maps.Element (Pos); begin Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); MAT.Frames.Insert (Frame => Client.Frames, Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth), Result => Client.Event.Frame); Handler.Probe.Execute (Client.Event); Client.Events.Insert (Client.Event); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name); Frame : Probe_Handler; procedure Add_Handler (Key : in String; Element : in out Probe_Handler); procedure Add_Handler (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0} with {1} attributes", Name, MAT.Types.Uint16'Image (Count)); if Name = "start" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("start", Frame); end if; end; end loop; if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- Read a list of event definitions from the stream and configure the reader. -- ------------------------------ procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is Count : MAT.Types.Uint16; begin if Client.Frame = null then Client.Frame := new MAT.Events.Frame_Info (512); end if; Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; exception when E : MAT.Readers.Marshaller.Buffer_Underflow_Error => Log.Error ("Not enough data in the message", E, True); end Read_Event_Definitions; end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Events.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes"); procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; Manager.Frames := MAT.Frames.Create_Root; end Initialize; -- ------------------------------ -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Probe_Handler; begin Handler.Probe := Probe; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Probes.Insert (Name, Handler); end Register_Probe; -- ------------------------------ -- Get the target events. -- ------------------------------ function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access is begin return Client.Events; end Get_Target_Events; procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Tick_Ref; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : constant access MAT.Events.Frame_Info := Client.Frame; begin Client.Event.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_THREAD_ID => Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_FRAME_PC => for I in 1 .. Count loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); end if; end loop; when others => null; end case; end; end loop; -- Convert the time in usec to make computation easier. Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000; Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec); Frame.Cur_Depth := Count; exception when E : others => Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count)); raise; end Read_Probe; procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is use type MAT.Events.Attribute_Table_Ptr; use type MAT.Events.Targets.Target_Events_Access; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); end if; if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Probe_Handler := Handler_Maps.Element (Pos); begin Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); MAT.Frames.Insert (Frame => Client.Frames, Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth), Result => Client.Event.Frame); Client.Events.Insert (Client.Event); Handler.Probe.Execute (Client.Event); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name); Frame : Probe_Handler; procedure Add_Handler (Key : in String; Element : in out Probe_Handler); procedure Add_Handler (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0} with {1} attributes", Name, MAT.Types.Uint16'Image (Count)); if Name = "start" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("start", Frame); end if; end; end loop; if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- Read a list of event definitions from the stream and configure the reader. -- ------------------------------ procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is Count : MAT.Types.Uint16; begin if Client.Frame = null then Client.Frame := new MAT.Events.Frame_Info (512); end if; Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; exception when E : MAT.Readers.Marshaller.Buffer_Underflow_Error => Log.Error ("Not enough data in the message", E, True); end Read_Event_Definitions; end MAT.Events.Probes;
Insert the event in the event list before the memory slot management so that we get the event Id
Insert the event in the event list before the memory slot management so that we get the event Id
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f46dce4553b1eddd16f72633da469a7cc7a1f7e4
samples/add_user.adb
samples/add_user.adb
----------------------------------------------------------------------- -- Add_User -- Example to add an object in the database -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Samples.User.Model; with ADO; with ADO.Drivers; with ADO.Sessions; with ADO.Sessions.Factory; with Util.Strings; with Util.Log.Loggers; with Ada.Text_IO; with Ada.Command_Line; procedure Add_User is use Samples.User.Model; function Get_Name (Email : in String) return String; Factory : ADO.Sessions.Factory.Session_Factory; function Get_Name (Email : in String) return String is Pos : constant Natural := Util.Strings.Index (Email, '@'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name; begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. ADO.Drivers.Initialize ("samples.properties"); if Ada.Command_Line.Argument_Count < 1 then Ada.Text_IO.Put_Line ("Usage: add_user user-email ..."); Ada.Text_IO.Put_Line ("Example: add_user [email protected]"); Ada.Command_Line.Set_Exit_Status (2); return; end if; -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; begin DB.Begin_Transaction; for I in 1 .. Ada.Command_Line.Argument_Count loop declare Email : constant String := Ada.Command_Line.Argument (I); Name : constant String := Get_Name (Email); User : User_Ref; begin User.Set_Name (Name); User.Set_Email (Email); User.Set_Description ("My friend " & Name); User.Set_Status (0); User.Save (DB); Ada.Text_IO.Put_Line ("User " & Name & " has id " & ADO.Identifier'Image (User.Get_Id)); end; end loop; DB.Commit; end; end Add_User;
----------------------------------------------------------------------- -- Add_User -- Example to add an object in the database -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Samples.User.Model; with ADO; with ADO.Drivers.Initializer; with ADO.Sessions; with ADO.Sessions.Factory; with Util.Strings; with Util.Log.Loggers; with Ada.Text_IO; with Ada.Command_Line; procedure Add_User is use Samples.User.Model; function Get_Name (Email : in String) return String; Factory : ADO.Sessions.Factory.Session_Factory; function Get_Name (Email : in String) return String is Pos : constant Natural := Util.Strings.Index (Email, '@'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name; procedure Initialize is new ADO.Drivers.Initializer (String, ADO.Drivers.Initialize); begin Util.Log.Loggers.Initialize ("samples.properties"); -- Initialize the database drivers. Initialize ("samples.properties"); if Ada.Command_Line.Argument_Count < 1 then Ada.Text_IO.Put_Line ("Usage: add_user user-email ..."); Ada.Text_IO.Put_Line ("Example: add_user [email protected]"); Ada.Command_Line.Set_Exit_Status (2); return; end if; -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("ado.database")); declare DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; begin DB.Begin_Transaction; for I in 1 .. Ada.Command_Line.Argument_Count loop declare Email : constant String := Ada.Command_Line.Argument (I); Name : constant String := Get_Name (Email); User : User_Ref; begin User.Set_Name (Name); User.Set_Email (Email); User.Set_Description ("My friend " & Name); User.Set_Status (0); User.Save (DB); Ada.Text_IO.Put_Line ("User " & Name & " has id " & ADO.Identifier'Image (User.Get_Id)); end; end loop; DB.Commit; end; end Add_User;
Update the initialization
Update the initialization
Ada
apache-2.0
stcarrez/ada-ado
4755e502b96ae78d7d6888a1304a1c1cc9df71ea
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- 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.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Users.Modules; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Member_List_Bean", Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Invitation_Bean", Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager; -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Member : AWA.Workspaces.Models.Workspace_Member_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- Create the member instance for this user. Member.Set_Workspace (WS); Member.Set_Member (User); Member.Set_Role ("Owner"); Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date)); Member.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; -- ------------------------------ -- Load the invitation from the access key and verify that the key is still valid. -- ------------------------------ procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; begin Log.Debug ("Loading invitation from key {0}", Key); Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; Inviter := AWA.Users.Models.User_Ref (Invitation.Get_Inviter); end Load_Invitation; -- ------------------------------ -- Accept the invitation identified by the access key. -- ------------------------------ procedure Accept_Invitation (Module : in Workspace_Module; Key : in String) is use type Ada.Calendar.Time; use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; Invitation : AWA.Workspaces.Models.Invitation_Ref; Invitee_Id : ADO.Identifier; Member : AWA.Workspaces.Models.Workspace_Member_Ref; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Log.Debug ("Accept invitation with key {0}", Key); Ctx.Start; Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Now then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Invitee_Id := DB_Key.Get_User.Get_Id; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", Invitee_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; -- Update the workspace member relation. Query.Clear; Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?"); Query.Add_Param (Invitee_Id); Query.Add_Param (Invitation.Get_Workspace.Get_Id); Member.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; -- The user who received the invitation is different from the user who is -- logged and accepted the validation. Since the key is verified, this is -- the same user but the user who accepted the invitation registered using -- another email address. if Invitee_Id /= User.Get_Id then Invitation.Set_Invitee (User); Member.Set_Member (User); Log.Info ("Invitation accepted by user with another email address"); end if; Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => Now)); Member.Save (DB); DB_Key.Delete (DB); Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False, Value => Now)); Invitation.Save (DB); Ctx.Commit; end Accept_Invitation; -- ------------------------------ -- Send the invitation to the user. -- ------------------------------ procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; Email : AWA.Users.Models.Email_Ref; Invitee : AWA.Users.Models.User_Ref; Invit : AWA.Workspaces.Models.Invitation_Ref; Member : AWA.Workspaces.Models.Workspace_Member_Ref; Email_Address : constant String := Invitation.Get_Email; begin Log.Info ("Sending invitation to {0}", Email_Address); Ctx.Start; if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (DB, Query, Found); if not Found then return; end if; Query.Clear; Query.Set_Filter ("o.email = ?"); Query.Add_Param (Email_Address); Email.Find (DB, Query, Found); if not Found then Email.Set_User_Id (0); Email.Set_Email (Email_Address); Email.Save (DB); Invitee.Set_Email (Email); Invitee.Set_Name (Email_Address); Invitee.Save (DB); Email.Set_User_Id (Invitee.Get_Id); Email.Save (DB); else Invitee.Load (DB, Email.Get_User_Id); end if; -- Create the workspace member relation. Query.Clear; Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?"); Query.Add_Param (Invitee.Get_Id); Query.Add_Param (WS.Get_Id); Member.Find (DB, Query, Found); if not Found then Member.Set_Member (Invitee); Member.Set_Workspace (WS); Member.Set_Role ("Invited"); Member.Save (DB); end if; -- Check for a previous invitation for the user and delete it. Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?"); Invit.Find (DB, Query, Found); if Found then Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key); Key.Delete (DB); if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then Invit.Delete (DB); end if; end if; Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key); Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB); Key.Save (DB); Invitation.Set_Access_Key (Key); Invitation.Set_Inviter (User); Invitation.Set_Invitee (Invitee); Invitation.Set_Workspace (WS); Invitation.Set_Create_Date (Ada.Calendar.Clock); Invitation.Save (DB); -- Send the email with the reset password key declare Event : AWA.Events.Module_Event; begin Event.Set_Parameter ("key", Key.Get_Access_Key); Event.Set_Parameter ("email", Email_Address); Event.Set_Parameter ("name", Invitee.Get_Name); Event.Set_Parameter ("message", Invitation.Get_Message); Event.Set_Parameter ("inviter", User.Get_Name); Event.Set_Event_Kind (Invite_User_Event.Kind); Module.Send_Event (Event); end; Ctx.Commit; end Send_Invitation; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- 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.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Users.Modules; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Member_List_Bean", Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Invitation_Bean", Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager; -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Member : AWA.Workspaces.Models.Workspace_Member_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- Create the member instance for this user. Member.Set_Workspace (WS); Member.Set_Member (User); Member.Set_Role ("Owner"); Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date)); Member.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; -- ------------------------------ -- Load the invitation from the access key and verify that the key is still valid. -- ------------------------------ procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; begin Log.Debug ("Loading invitation from key {0}", Key); Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; Inviter := AWA.Users.Models.User_Ref (Invitation.Get_Inviter); end Load_Invitation; -- ------------------------------ -- Accept the invitation identified by the access key. -- ------------------------------ procedure Accept_Invitation (Module : in Workspace_Module; Key : in String) is use type Ada.Calendar.Time; use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; Invitation : AWA.Workspaces.Models.Invitation_Ref; Invitee_Id : ADO.Identifier; Workspace_Id : ADO.Identifier; Member : AWA.Workspaces.Models.Workspace_Member_Ref; User_Member : AWA.Workspaces.Models.Workspace_Member_Ref; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Log.Debug ("Accept invitation with key {0}", Key); Ctx.Start; -- Get the access key and verify its validity. Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist", Key); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Now then Log.Info ("Invitation key {0} has expired", Key); raise Not_Found; end if; -- Find the invitation associated with the access key. Invitee_Id := DB_Key.Get_User.Get_Id; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", Invitee_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn", Key); raise Not_Found; end if; Workspace_Id := Invitation.Get_Workspace.Get_Id; -- Update the workspace member relation. Query.Clear; Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?"); Query.Add_Param (Invitee_Id); Query.Add_Param (Workspace_Id); Member.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn", Key); raise Not_Found; end if; Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => Now)); Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False, Value => Now)); -- The user who received the invitation is different from the user who is -- logged and accepted the validation. Since the key is verified, this is -- the same user but the user who accepted the invitation registered using -- another email address. if Invitee_Id /= User.Get_Id then -- Check whether the user is not already part of the workspace. Query.Clear; Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?"); Query.Add_Param (User.Get_Id); Query.Add_Param (Workspace_Id); User_Member.Find (DB, Query, Found); if Found then Member.Delete (DB); Invitation.Delete (DB); Log.Info ("Invitation accepted by user who is already a member"); else Member.Set_Member (User); Log.Info ("Invitation accepted by user with another email address"); end if; Invitation.Set_Invitee (User); end if; if not Member.Is_Null then Member.Save (DB); end if; DB_Key.Delete (DB); if not Invitation.Is_Null then Invitation.Save (DB); end if; Ctx.Commit; end Accept_Invitation; -- ------------------------------ -- Send the invitation to the user. -- ------------------------------ procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; Email : AWA.Users.Models.Email_Ref; Invitee : AWA.Users.Models.User_Ref; Invit : AWA.Workspaces.Models.Invitation_Ref; Member : AWA.Workspaces.Models.Workspace_Member_Ref; Email_Address : constant String := Invitation.Get_Email; begin Log.Info ("Sending invitation to {0}", Email_Address); Ctx.Start; if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (DB, Query, Found); if not Found then return; end if; Query.Clear; Query.Set_Filter ("o.email = ?"); Query.Add_Param (Email_Address); Email.Find (DB, Query, Found); if not Found then Email.Set_User_Id (0); Email.Set_Email (Email_Address); Email.Save (DB); Invitee.Set_Email (Email); Invitee.Set_Name (Email_Address); Invitee.Save (DB); Email.Set_User_Id (Invitee.Get_Id); Email.Save (DB); else Invitee.Load (DB, Email.Get_User_Id); end if; -- Create the workspace member relation. Query.Clear; Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?"); Query.Add_Param (Invitee.Get_Id); Query.Add_Param (WS.Get_Id); Member.Find (DB, Query, Found); if not Found then Member.Set_Member (Invitee); Member.Set_Workspace (WS); Member.Set_Role ("Invited"); Member.Save (DB); end if; -- Check for a previous invitation for the user and delete it. Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?"); Invit.Find (DB, Query, Found); if Found then Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key); Key.Delete (DB); if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then Invit.Delete (DB); end if; end if; Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key); Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB); Key.Save (DB); Invitation.Set_Access_Key (Key); Invitation.Set_Inviter (User); Invitation.Set_Invitee (Invitee); Invitation.Set_Workspace (WS); Invitation.Set_Create_Date (Ada.Calendar.Clock); Invitation.Save (DB); -- Send the email with the reset password key declare Event : AWA.Events.Module_Event; begin Event.Set_Parameter ("key", Key.Get_Access_Key); Event.Set_Parameter ("email", Email_Address); Event.Set_Parameter ("name", Invitee.Get_Name); Event.Set_Parameter ("message", Invitation.Get_Message); Event.Set_Parameter ("inviter", User.Get_Name); Event.Set_Event_Kind (Invite_User_Event.Kind); Module.Send_Event (Event); end; Ctx.Commit; end Send_Invitation; end AWA.Workspaces.Modules;
Fix the accept invitation procedure to take into account a user that is already registered but accepted an invitation with another email address
Fix the accept invitation procedure to take into account a user that is already registered but accepted an invitation with another email address
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
51adc6ffc4dcd032cbd46bbe74eafb5bcebc3377
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Objects; with ADO.Sessions; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; private with Ada.Strings.Unbounded; -- == Events == -- The *workspaces* module provides several events that are posted when some action are performed. -- -- === invite-user === -- This event is posted when an invitation is created for a user. The event can be used to -- send the associated invitation email to the invitee. The event contains the following -- attributes: -- -- key -- email -- name -- message -- inviter -- -- === accept-invitation === -- This event is posted when an invitation is accepted by a user. package AWA.Workspaces.Modules is subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array; Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- The configuration parameter that defines the list of permissions to grant -- to a user when his workspace is created. PARAM_PERMISSIONS_LIST : constant String := "permissions_list"; -- Permission to create a workspace. package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create"); package ACL_Invite_User is new Security.Permissions.Definition ("workspace-invite-user"); package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Workspace_Module; Props : in ASF.Applications.Config); -- Get the list of permissions for the workspace owner. function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array; -- Get the workspace module. function Get_Workspace_Module return Workspace_Module_Access; -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Create a workspace for the user. procedure Create_Workspace (Module : in Workspace_Module; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); -- Add a list of permissions for all the users of the workspace that have the appropriate -- role. Workspace members will be able to access the given database entity for the -- specified list of permissions. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; List : in Security.Permissions.Permission_Index_Array); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; -- The list of permissions to grant to a user who creates the workspace. Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Objects; with ADO.Sessions; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; private with Ada.Strings.Unbounded; -- == Events == -- The *workspaces* module provides several events that are posted when some action are performed. -- -- === invite-user === -- This event is posted when an invitation is created for a user. The event can be used to -- send the associated invitation email to the invitee. The event contains the following -- attributes: -- -- key -- email -- name -- message -- inviter -- -- === accept-invitation === -- This event is posted when an invitation is accepted by a user. package AWA.Workspaces.Modules is subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array; Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- The configuration parameter that defines the list of permissions to grant -- to a user when his workspace is created. PARAM_PERMISSIONS_LIST : constant String := "permissions_list"; -- Permission to create a workspace. package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create"); package ACL_Invite_User is new Security.Permissions.Definition ("workspace-invite-user"); package ACL_Delete_User is new Security.Permissions.Definition ("workspace-delete-user"); package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Workspace_Module; Props : in ASF.Applications.Config); -- Get the list of permissions for the workspace owner. function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array; -- Get the workspace module. function Get_Workspace_Module return Workspace_Module_Access; -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Create a workspace for the user. procedure Create_Workspace (Module : in Workspace_Module; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); -- Add a list of permissions for all the users of the workspace that have the appropriate -- role. Workspace members will be able to access the given database entity for the -- specified list of permissions. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; List : in Security.Permissions.Permission_Index_Array); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; -- The list of permissions to grant to a user who creates the workspace. Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Workspaces.Modules;
Declare the ACL_Delete_User permission
Declare the ACL_Delete_User permission
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0b8f86fd3802dba14dd2c0dc03eaea18976d9dbb
awa/samples/src/atlas.ads
awa/samples/src/atlas.ads
----------------------------------------------------------------------- -- atlas -- ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- package Atlas is end Atlas;
----------------------------------------------------------------------- -- atlas -- Atlas demo ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- package Atlas is pragma Pure; end Atlas;
Add pragma Pure
Add pragma Pure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e0b60cc45f657e3d422724b380012b07dffa31b1
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 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); Box.Get ("voip", Gateway.Voip); Box.Get ("iptv", Gateway.IPtv); 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;
----------------------------------------------------------------------- -- 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 Util.Http.Clients; 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 "="; package Int_Property renames Util.Properties.Basic.Integer_Property; package Bool_Property renames Util.Properties.Basic.Boolean_Property; -- ------------------------------ -- 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 := Int_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"); Gw.Value.Enable := Bool_Property.Get (Config, Base & ".enable", True); 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); Bool_Property.Set (Config, Base & ".enable", Gw.Value.Enable); 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); Box.Get ("voip", Gateway.Voip); Box.Get ("iptv", Gateway.IPtv); Box.Get ("hosts", Gateway.Hosts); if Gateway.Device.Exists ("device.serialnumber") then Gateway.Serial := Gateway.Device.Get ("device.serialnumber"); end if; exception when Util.Http.Clients.Connection_Error => Log.Error ("Cannot connect to {0}", To_String (Gateway.IP)); 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; Mode : in Iterate_Type := ITER_ALL; Process : not null access procedure (G : in out Gateway_Type)) is Expect : constant Boolean := Mode = ITER_ENABLE; begin for G of List loop if Mode = ITER_ALL or else G.Value.Enable = Expect then Process (G.Value.all); end if; 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;
Add a Enable boolean value on each gateway Add a Hosts properties that contain results of hosts API Update Iterate on gateways to iterate only on gateways that are enabled, disabled or all
Add a Enable boolean value on each gateway Add a Hosts properties that contain results of hosts API Update Iterate on gateways to iterate only on gateways that are enabled, disabled or all
Ada
apache-2.0
stcarrez/bbox-ada-api
69af9b4b575a0878d95988d96b49e610e4d61c87
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 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.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)); begin Controller.Port := Integer'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; 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; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_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;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 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.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)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; 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; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural 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;
Implement the Set_Port procedure
Implement the Set_Port procedure
Ada
apache-2.0
stcarrez/ada-ado
bd57e00f1fdc0a7a2add55bfaaeb961e5f102e4e
src/asf-contexts-exceptions.adb
src/asf-contexts-exceptions.adb
----------------------------------------------------------------------- -- asf-contexts-exceptions -- Exception handlers in faces context -- Copyright (C) 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 Ada.Unchecked_Deallocation; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; package body ASF.Contexts.Exceptions is -- ------------------------------ -- Take action to handle the <b>Exception_Event</b> instances that have been queued by -- calls to <b>Application.Publish_Event</b>. -- -- This operation is called after each ASF phase by the life cycle manager. -- ------------------------------ procedure Handle (Handler : in out Exception_Handler) is pragma Unreferenced (Handler); use ASF.Applications; use type ASF.Contexts.Faces.Faces_Context_Access; function Get_Message (Event : in Events.Exceptions.Exception_Event'Class; Context : in ASF.Contexts.Faces.Faces_Context'Class) return ASF.Applications.Messages.Message; procedure Process (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Get a localized message for the exception -- ------------------------------ function Get_Message (Event : in Events.Exceptions.Exception_Event'Class; Context : in ASF.Contexts.Faces.Faces_Context'Class) return ASF.Applications.Messages.Message is Name : constant String := Event.Get_Exception_Name; Msg : constant String := Event.Get_Exception_Message; Pos : constant Util.Strings.Maps.Cursor := Handler.Mapping.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Messages.Factory.Get_Message (Context => Context, Message_Id => Util.Strings.Maps.Element (Pos), Param1 => Msg); elsif Msg'Length = 0 then return Messages.Factory.Get_Message (Context => Context, Message_Id => EXCEPTION_MESSAGE_BASIC_ID, Param1 => Name); else return Messages.Factory.Get_Message (Context => Context, Message_Id => EXCEPTION_MESSAGE_EXTENDED_ID, Param1 => Name, Param2 => Msg); end if; end Get_Message; -- ------------------------------ -- Process each exception event and add a message in the faces context. -- ------------------------------ procedure Process (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Msg : constant Messages.Message := Get_Message (Event, Context); begin Context.Add_Message (Client_Id => "", Message => Msg); Remove := True; end Process; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return; end if; if Context.Get_Response_Completed then return; end if; Context.Iterate_Exception (Process'Access); end Handle; -- ------------------------------ -- Set the message id to be used when a given exception name is raised. -- ------------------------------ procedure Set_Message (Handler : in out Exception_Handler; Name : in String; Message_Id : in String) is begin Handler.Mapping.Insert (Name, Message_Id); end Set_Message; -- ------------------------------ -- Queue an exception event to the exception handler. The exception event will be -- processed at the end of the current ASF phase. -- ------------------------------ procedure Queue_Exception (Queue : in out Exception_Queue; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Queue.Unhandled_Events.Append (ASF.Events.Exceptions.Create_Exception_Event (Ex)); end Queue_Exception; -- ------------------------------ -- Clear the exception queue. -- ------------------------------ overriding procedure Finalize (Queue : in out Exception_Queue) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Exceptions.Exception_Event'Class, Name => ASF.Events.Exceptions.Exception_Event_Access); Len : Natural; begin loop Len := Natural (Queue.Unhandled_Events.Length); exit when Len = 0; declare Event : ASF.Events.Exceptions.Exception_Event_Access := Queue.Unhandled_Events.Element (Len); begin Free (Event); Queue.Unhandled_Events.Delete (Len); end; end loop; end Finalize; end ASF.Contexts.Exceptions;
----------------------------------------------------------------------- -- asf-contexts-exceptions -- Exception handlers in faces context -- Copyright (C) 2011, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; package body ASF.Contexts.Exceptions is -- ------------------------------ -- Take action to handle the <b>Exception_Event</b> instances that have been queued by -- calls to <b>Application.Publish_Event</b>. -- -- This operation is called after each ASF phase by the life cycle manager. -- ------------------------------ procedure Handle (Handler : in out Exception_Handler) is use ASF.Applications; use type ASF.Contexts.Faces.Faces_Context_Access; function Get_Message (Event : in Events.Exceptions.Exception_Event'Class; Context : in ASF.Contexts.Faces.Faces_Context'Class) return ASF.Applications.Messages.Message; procedure Process (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Get a localized message for the exception -- ------------------------------ function Get_Message (Event : in Events.Exceptions.Exception_Event'Class; Context : in ASF.Contexts.Faces.Faces_Context'Class) return ASF.Applications.Messages.Message is Name : constant String := Event.Get_Exception_Name; Msg : constant String := Event.Get_Exception_Message; Pos : constant Util.Strings.Maps.Cursor := Handler.Mapping.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Messages.Factory.Get_Message (Context => Context, Message_Id => Util.Strings.Maps.Element (Pos), Param1 => Msg); elsif Msg'Length = 0 then return Messages.Factory.Get_Message (Context => Context, Message_Id => EXCEPTION_MESSAGE_BASIC_ID, Param1 => Name); else return Messages.Factory.Get_Message (Context => Context, Message_Id => EXCEPTION_MESSAGE_EXTENDED_ID, Param1 => Name, Param2 => Msg); end if; end Get_Message; -- ------------------------------ -- Process each exception event and add a message in the faces context. -- ------------------------------ procedure Process (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Msg : constant Messages.Message := Get_Message (Event, Context); begin Context.Add_Message (Client_Id => "", Message => Msg); Remove := True; end Process; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return; end if; if Context.Get_Response_Completed then return; end if; Context.Iterate_Exception (Process'Access); end Handle; -- ------------------------------ -- Set the message id to be used when a given exception name is raised. -- ------------------------------ procedure Set_Message (Handler : in out Exception_Handler; Name : in String; Message_Id : in String) is begin Handler.Mapping.Insert (Name, Message_Id); end Set_Message; -- ------------------------------ -- Queue an exception event to the exception handler. The exception event will be -- processed at the end of the current ASF phase. -- ------------------------------ procedure Queue_Exception (Queue : in out Exception_Queue; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Queue.Unhandled_Events.Append (ASF.Events.Exceptions.Create_Exception_Event (Ex)); end Queue_Exception; -- ------------------------------ -- Clear the exception queue. -- ------------------------------ overriding procedure Finalize (Queue : in out Exception_Queue) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Exceptions.Exception_Event'Class, Name => ASF.Events.Exceptions.Exception_Event_Access); Len : Natural; begin loop Len := Natural (Queue.Unhandled_Events.Length); exit when Len = 0; declare Event : ASF.Events.Exceptions.Exception_Event_Access := Queue.Unhandled_Events.Element (Len); begin Free (Event); Queue.Unhandled_Events.Delete (Len); end; end loop; end Finalize; end ASF.Contexts.Exceptions;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f074160b739452efa15b0aef968028a30dbb0fa2
src/atlas-server.adb
src/atlas-server.adb
----------------------------------------------------------------------- -- atlas-server -- Application server -- Copyright (C) 2011, 2012, 2013, 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.Exceptions; with Util.Log.Loggers; with AWS.Net.SSL; 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; procedure Setup is new AWA.Setup.Applications.Configure (Atlas.Applications.Application'Class, Atlas.Applications.Application_Access, Atlas.Applications.Initialize); 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; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); Setup (WS, App, "atlas", Atlas.Applications.CONTEXT_PATH); if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OAuth2/OpenID connector to " & "connect to OAuth2/OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); end if; 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, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with ADO.Drivers; with AWS.Net.SSL; 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; procedure Setup is new AWA.Setup.Applications.Configure (Atlas.Applications.Application'Class, Atlas.Applications.Application_Access, Atlas.Applications.Initialize); 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 ADO.Drivers.Initialize; WS.Configure (Configure'Access); WS.Start; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); Setup (WS, App, "atlas", Atlas.Applications.CONTEXT_PATH); if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OAuth2/OpenID connector to " & "connect to OAuth2/OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); end if; 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;
Call ADO.Drivers.Initialize to setup all known database drivers
Call ADO.Drivers.Initialize to setup all known database drivers
Ada
apache-2.0
stcarrez/atlas
0f52ee83b175b4b28ae49fb45375e0866a9eaf98
src/port_specification-json.adb
src/port_specification-json.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Utilities; with Ada.Characters.Latin_1; package body Port_Specification.Json is package UTL renames Utilities; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- describe_port -------------------------------------------------------------------------------------------- procedure describe_port (specs : Portspecs; dossier : TIO.File_Type; bucket : String; index : Positive) is fpcval : constant String := fpc_value (specs.generated, specs.equivalent_fpc_port); nvar : constant Natural := specs.get_number_of_variants; begin TIO.Put (dossier, UTL.json_object (True, 3, index) & UTL.json_nvpair_string ("bucket", bucket, 1, pad) & UTL.json_nvpair_string ("namebase", specs.get_namebase, 2, pad) & UTL.json_nvpair_string ("version", specs.get_field_value (sp_version), 3, pad) & homepage_line (specs) & UTL.json_nvpair_string ("FPC", fpcval, 3, pad) & UTL.json_nvpair_complex ("keywords", describe_keywords (specs), 3, pad) & UTL.json_nvpair_complex ("distfile", describe_distfiles (specs), 3, pad) & specs.get_json_contacts & describe_Common_Platform_Enumeration (specs) & UTL.json_name_complex ("variants", 4, pad) & UTL.json_array (True, pad + 1) ); for x in 1 .. nvar loop declare varstr : constant String := specs.get_list_item (Port_Specification.sp_variants, x); sdesc : constant String := escape_tagline (specs.get_tagline (varstr)); spray : constant String := describe_subpackages (specs, varstr); begin TIO.Put (dossier, UTL.json_object (True, pad + 2, x) & UTL.json_nvpair_string ("label", varstr, 1, pad + 3) & UTL.json_nvpair_string ("sdesc", sdesc, 2, pad + 3) & UTL.json_nvpair_complex ("spkgs", spray, 3, pad + 3) & UTL.json_object (False, pad + 2, x) ); end; end loop; TIO.Put (dossier, UTL.json_array (False, pad + 1) & UTL.json_object (False, 3, index) ); end describe_port; -------------------------------------------------------------------------------------------- -- fpc_value -------------------------------------------------------------------------------------------- function fpc_value (is_generated : Boolean; raw_value : String) return String is begin if is_generated then return "generated"; else return raw_value; end if; end fpc_value; -------------------------------------------------------------------------------------------- -- describe_keywords -------------------------------------------------------------------------------------------- function describe_keywords (specs : Portspecs) return String is raw : constant String := specs.get_field_value (Port_Specification.sp_keywords); innerquote : constant String := HT.replace_char (S => HT.replace_char (raw, LAT.Comma, LAT.Quotation & LAT.Comma), focus => LAT.Space, substring => LAT.Space & LAT.Quotation); begin return "[ " & LAT.Quotation & innerquote & LAT.Quotation & " ]"; end describe_keywords; -------------------------------------------------------------------------------------------- -- describe_distfiles -------------------------------------------------------------------------------------------- function describe_distfiles (specs : Portspecs) return String is numfiles : constant Natural := specs.get_list_length (Port_Specification.sp_distfiles); result : HT.Text := HT.SUS ("[ "); begin for x in 1 .. numfiles loop if x > 1 then HT.SU.Append (result, ", "); end if; HT.SU.Append (result, LAT.Quotation & specs.get_repology_distfile (x) & LAT.Quotation); end loop; return HT.USS (result) & " ]"; end describe_distfiles; -------------------------------------------------------------------------------------------- -- describe_subpackages -------------------------------------------------------------------------------------------- function describe_subpackages (specs : Portspecs; variant : String) return String is numpkg : constant Natural := specs.get_subpackage_length (variant); result : HT.Text := HT.SUS ("[ "); begin for x in 1 .. numpkg loop if x > 1 then HT.SU.Append (result, ", "); end if; HT.SU.Append (result, LAT.Quotation & specs.get_subpackage_item (variant, x) & LAT.Quotation); end loop; return HT.USS (result) & " ]"; end describe_subpackages; -------------------------------------------------------------------------------------------- -- escape_tagline -------------------------------------------------------------------------------------------- function escape_tagline (raw : String) return String is focus : constant String := LAT.Reverse_Solidus & LAT.Quotation & LAT.Solidus & LAT.BS & LAT.FF & LAT.LF & LAT.CR & LAT.HT; curlen : Natural := raw'Length; result : String (1 .. raw'Length * 2) := (others => ' '); begin result (1 .. curlen) := raw; for x in focus'Range loop if HT.count_char (result (1 .. curlen), focus (x)) > 0 then declare newstr : String := HT.replace_char (result (1 .. curlen), focus (x), LAT.Reverse_Solidus & focus (x)); begin curlen := newstr'Length; result (1 .. curlen) := newstr; end; end if; end loop; return result (1 .. curlen); end escape_tagline; -------------------------------------------------------------------------------------------- -- homepage_line -------------------------------------------------------------------------------------------- function homepage_line (specs : Portspecs) return String is homepage : constant String := specs.get_field_value (sp_homepage); begin if homepage = homepage_none or else specs.repology_sucks then return ""; end if; return UTL.json_nvpair_string ("homepage", specs.get_field_value (sp_homepage), 3, pad); end homepage_line; -------------------------------------------------------------------------------------------- -- describe_Common_Platform_Enumeration -------------------------------------------------------------------------------------------- function describe_Common_Platform_Enumeration (specs : Portspecs) return String is function retrieve (key : String; default_value : String) return String; function form_object (product, vendor : String) return String; function retrieve (key : String; default_value : String) return String is key_text : HT.Text := HT.SUS (key); begin if specs.catch_all.Contains (key_text) then return HT.USS (specs.catch_all.Element (key_text).list.First_Element); else return default_value; end if; end retrieve; function form_object (product, vendor : String) return String is data1 : String := UTL.json_nvpair_string ("product", product, 1, 0); -- trailing LF data2 : String := UTL.json_nvpair_string ("vendor", vendor, 1, 0); -- trailing LF begin return "{" & data1 (data1'First .. data1'Last - 1) & LAT.Comma & data2 (data2'First .. data2'Last - 1) & " }"; end form_object; begin if not specs.uses.Contains (HT.SUS ("cpe")) then return ""; end if; declare cpe_product : String := retrieve ("CPE_PRODUCT", HT.lowercase (specs.get_namebase)); cpe_vendor : String := retrieve ("CPE_VENDOR", cpe_product); begin return UTL.json_nvpair_complex ("cpe", form_object (cpe_product, cpe_vendor), 3, pad); end; end describe_Common_Platform_Enumeration; end Port_Specification.Json;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Utilities; with Ada.Characters.Latin_1; with HelperText; package body Port_Specification.Json is package LAT renames Ada.Characters.Latin_1; package UTL renames Utilities; package HT renames HelperText; -------------------------------------------------------------------------------------------- -- describe_port -------------------------------------------------------------------------------------------- procedure describe_port (specs : Portspecs; dossier : TIO.File_Type; bucket : String; index : Positive) is fpcval : constant String := fpc_value (specs.generated, specs.equivalent_fpc_port); nvar : constant Natural := specs.get_number_of_variants; begin TIO.Put (dossier, UTL.json_object (True, 3, index) & UTL.json_nvpair_string ("bucket", bucket, 1, pad) & UTL.json_nvpair_string ("namebase", specs.get_namebase, 2, pad) & UTL.json_nvpair_string ("version", specs.get_field_value (sp_version), 3, pad) & homepage_line (specs) & UTL.json_nvpair_string ("FPC", fpcval, 3, pad) & UTL.json_nvpair_complex ("keywords", describe_keywords (specs), 3, pad) & UTL.json_nvpair_complex ("distfile", describe_distfiles (specs), 3, pad) & specs.get_json_contacts & describe_Common_Platform_Enumeration (specs) & UTL.json_name_complex ("variants", 4, pad) & UTL.json_array (True, pad + 1) ); for x in 1 .. nvar loop declare varstr : constant String := specs.get_list_item (Port_Specification.sp_variants, x); sdesc : constant String := escape_tagline (specs.get_tagline (varstr)); spray : constant String := describe_subpackages (specs, varstr); begin TIO.Put (dossier, UTL.json_object (True, pad + 2, x) & UTL.json_nvpair_string ("label", varstr, 1, pad + 3) & UTL.json_nvpair_string ("sdesc", sdesc, 2, pad + 3) & UTL.json_nvpair_complex ("spkgs", spray, 3, pad + 3) & UTL.json_object (False, pad + 2, x) ); end; end loop; TIO.Put (dossier, UTL.json_array (False, pad + 1) & UTL.json_object (False, 3, index) ); end describe_port; -------------------------------------------------------------------------------------------- -- fpc_value -------------------------------------------------------------------------------------------- function fpc_value (is_generated : Boolean; raw_value : String) return String is begin if is_generated then return "generated"; else return raw_value; end if; end fpc_value; -------------------------------------------------------------------------------------------- -- describe_keywords -------------------------------------------------------------------------------------------- function describe_keywords (specs : Portspecs) return String is raw : constant String := specs.get_field_value (Port_Specification.sp_keywords); innerquote : constant String := HT.replace_char (S => HT.replace_char (raw, LAT.Comma, LAT.Quotation & LAT.Comma), focus => LAT.Space, substring => LAT.Space & LAT.Quotation); begin return "[ " & LAT.Quotation & innerquote & LAT.Quotation & " ]"; end describe_keywords; -------------------------------------------------------------------------------------------- -- describe_distfiles -------------------------------------------------------------------------------------------- function describe_distfiles (specs : Portspecs) return String is numfiles : constant Natural := specs.get_list_length (Port_Specification.sp_distfiles); result : HT.Text := HT.SUS ("[ "); begin for x in 1 .. numfiles loop if x > 1 then HT.SU.Append (result, ", "); end if; HT.SU.Append (result, LAT.Quotation & specs.get_repology_distfile (x) & LAT.Quotation); end loop; return HT.USS (result) & " ]"; end describe_distfiles; -------------------------------------------------------------------------------------------- -- describe_subpackages -------------------------------------------------------------------------------------------- function describe_subpackages (specs : Portspecs; variant : String) return String is numpkg : constant Natural := specs.get_subpackage_length (variant); result : HT.Text := HT.SUS ("[ "); begin for x in 1 .. numpkg loop if x > 1 then HT.SU.Append (result, ", "); end if; HT.SU.Append (result, LAT.Quotation & specs.get_subpackage_item (variant, x) & LAT.Quotation); end loop; return HT.USS (result) & " ]"; end describe_subpackages; -------------------------------------------------------------------------------------------- -- escape_tagline -------------------------------------------------------------------------------------------- function escape_tagline (raw : String) return String is focus : constant String := LAT.Reverse_Solidus & LAT.Quotation & LAT.Solidus & LAT.BS & LAT.FF & LAT.LF & LAT.CR & LAT.HT; curlen : Natural := raw'Length; result : String (1 .. raw'Length * 2) := (others => ' '); begin result (1 .. curlen) := raw; for x in focus'Range loop if HT.count_char (result (1 .. curlen), focus (x)) > 0 then declare newstr : String := HT.replace_char (result (1 .. curlen), focus (x), LAT.Reverse_Solidus & focus (x)); begin curlen := newstr'Length; result (1 .. curlen) := newstr; end; end if; end loop; return result (1 .. curlen); end escape_tagline; -------------------------------------------------------------------------------------------- -- homepage_line -------------------------------------------------------------------------------------------- function homepage_line (specs : Portspecs) return String is homepage : constant String := specs.get_field_value (sp_homepage); begin if homepage = homepage_none or else specs.repology_sucks then return ""; end if; return UTL.json_nvpair_string ("homepage", specs.get_field_value (sp_homepage), 3, pad); end homepage_line; -------------------------------------------------------------------------------------------- -- describe_Common_Platform_Enumeration -------------------------------------------------------------------------------------------- function describe_Common_Platform_Enumeration (specs : Portspecs) return String is function retrieve (key : String; default_value : String) return String; function form_object return String; procedure maybe_push (json_key, cpe_key, default_value : String); procedure always_push (json_key, value : String); pairs : string_crate.Vector; function retrieve (key : String; default_value : String) return String is key_text : HT.Text := HT.SUS (key); begin if specs.catch_all.Contains (key_text) then return HT.USS (specs.catch_all.Element (key_text).list.First_Element); else return default_value; end if; end retrieve; procedure always_push (json_key, value : String) is begin pairs.Append (HT.SUS (json_key & "=" & value)); end always_push; procedure maybe_push (json_key, cpe_key, default_value : String) is cpe_key_text : HT.Text := HT.SUS (cpe_key); cpe_value : HT.Text; begin if specs.catch_all.Contains (cpe_key_text) then cpe_value := specs.catch_all.Element (cpe_key_text).list.First_Element; if not HT.equivalent (cpe_value, default_value) then pairs.Append (HT.SUS (json_key & "=" & HT.USS (cpe_value))); end if; end if; end maybe_push; function form_object return String is procedure dump (position : string_crate.Cursor); tracker : Natural := 0; guts : HT.Text; procedure dump (position : string_crate.Cursor) is both : String := HT.USS (string_crate.Element (position)); key : String := HT.part_1 (both, "="); value : String := HT.part_2 (both, "="); data : String := UTL.json_nvpair_string (key, value, 1, 0); -- trailing LF begin tracker := tracker + 1; if tracker > 1 then HT.SU.Append (guts, LAT.Comma); end if; HT.SU.Append (guts, data (data'First .. data'Last - 1)); end dump; begin pairs.Iterate (dump'Access); return "{" & HT.USS (guts) & " }"; end form_object; begin if not specs.uses.Contains (HT.SUS ("cpe")) then return ""; end if; maybe_push ("part", "CPE_PART", "a"); declare cpe_product : String := retrieve ("CPE_PRODUCT", HT.lowercase (specs.get_namebase)); cpe_vendor : String := retrieve ("CPE_VENDOR", cpe_product); begin -- probably should be vendor then product, but this was the original order -- of repology json. Maintain order to avoid massive diff. always_push ("product", cpe_product); always_push ("vendor", cpe_vendor); end; maybe_push ("version", "CPE_VERSION", HT.USS (specs.version)); maybe_push ("update", "CPE_UPDATE", ""); maybe_push ("edition", "CPE_EDITION", ""); maybe_push ("lang", "CPE_LANG", ""); maybe_push ("sw_edition", "CPE_SW_EDITION", ""); maybe_push ("target_sw", "CPE_TARGET_SW", "take-anything"); maybe_push ("target_hw", "CPE_TARGET_HW", "x86-x86-arm64"); maybe_push ("other", "CPE_OTHER", HT.USS (specs.version)); return UTL.json_nvpair_complex ("cpe", form_object, 3, pad); end describe_Common_Platform_Enumeration; end Port_Specification.Json;
expand CPE output to repology.json
expand CPE output to repology.json If any of the new 9 fields are defined to something other than its default, add it to the json object. any definition of CPE_TARGET_SW and CPE_TARGET_HW are always taken (no default)
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
600e1d8a45f91067b62419646d29b8eddcf5e710
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
Document the role based policy
Document the role based policy
Ada
apache-2.0
stcarrez/ada-security
d6ce35f7c3b68e186658fe1fb2f519d8d4037d3c
src/asf-converters-sizes.adb
src/asf-converters-sizes.adb
----------------------------------------------------------------------- -- asf-converters-sizes -- Size converter -- 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.Exceptions; with Ada.Strings.Unbounded; with Util.Locales; with Util.Strings; with Util.Properties.Bundles; with ASF.Locales; with ASF.Utils; with ASF.Applications.Main; package body ASF.Converters.Sizes is ONE_KB : constant Long_Long_Integer := 1_024; ONE_MB : constant Long_Long_Integer := ONE_KB * 1_024; ONE_GB : constant Long_Long_Integer := ONE_MB * 1_024; UNIT_GB : aliased constant String := "size_giga_bytes"; UNIT_MB : aliased constant String := "size_mega_bytes"; UNIT_KB : aliased constant String := "size_kilo_bytes"; UNIT_B : aliased constant String := "size_bytes"; -- ------------------------------ -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- ------------------------------ function To_String (Convert : in Size_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in Util.Beans.Objects.Object) return String is pragma Unreferenced (Convert); Bundle : ASF.Locales.Bundle; Locale : constant Util.Locales.Locale := Context.Get_Locale; begin begin Context.Get_Application.Load_Bundle (Name => "sizes", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); exception when E : Util.Properties.Bundles.NO_BUNDLE => Component.Log_Error ("Cannot localize sizes: {0}", Ada.Exceptions.Exception_Message (E)); end; -- Convert the value as an integer here so that we can raise -- the Invalid_Conversion exception. declare Size : constant Long_Long_Integer := Util.Beans.Objects.To_Long_Long_Integer (Value); Val : Integer; Values : ASF.Utils.Object_Array (1 .. 1); Result : Ada.Strings.Unbounded.Unbounded_String; Unit : Util.Strings.Name_Access; begin if Size >= ONE_GB then Val := Integer ((Size + ONE_GB / 2) / ONE_GB); Unit := UNIT_GB'Access; elsif Size >= ONE_MB then Val := Integer ((Size + ONE_MB / 2) / ONE_MB); Unit := UNIT_MB'Access; elsif Size >= ONE_KB then Val := Integer ((Size + ONE_KB / 2) / ONE_KB); Unit := UNIT_KB'Access; else Val := Integer (Size); Unit := UNIT_B'Access; end if; Values (1) := Util.Beans.Objects.To_Object (Val); ASF.Utils.Formats.Format (Bundle.Get (Unit.all), Values, Result); return Ada.Strings.Unbounded.To_String (Result); end; exception when E : others => raise ASF.Converters.Invalid_Conversion with Ada.Exceptions.Exception_Message (E); end To_String; -- ------------------------------ -- Convert the date string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- ------------------------------ function To_Object (Convert : in Size_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Convert, Context, Value); begin Component.Log_Error ("Conversion of string to a size is not implemented"); raise ASF.Converters.Invalid_Conversion with "Not implemented"; return Util.Beans.Objects.Null_Object; end To_Object; end ASF.Converters.Sizes;
----------------------------------------------------------------------- -- asf-converters-sizes -- Size converter -- 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.Exceptions; with Ada.Strings.Unbounded; with Util.Locales; with Util.Strings; with Util.Properties.Bundles; with ASF.Locales; with ASF.Utils; with ASF.Applications.Main; package body ASF.Converters.Sizes is ONE_KB : constant Long_Long_Integer := 1_024; ONE_MB : constant Long_Long_Integer := ONE_KB * 1_024; ONE_GB : constant Long_Long_Integer := ONE_MB * 1_024; UNIT_GB : aliased constant String := "size_giga_bytes"; UNIT_MB : aliased constant String := "size_mega_bytes"; UNIT_KB : aliased constant String := "size_kilo_bytes"; UNIT_B : aliased constant String := "size_bytes"; -- ------------------------------ -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- ------------------------------ function To_String (Convert : in Size_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in Util.Beans.Objects.Object) return String is pragma Unreferenced (Convert); Bundle : ASF.Locales.Bundle; Locale : constant Util.Locales.Locale := Context.Get_Locale; begin begin ASF.Applications.Main.Load_Bundle (Context.Get_Application.all, Name => "sizes", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); exception when E : Util.Properties.Bundles.NO_BUNDLE => Component.Log_Error ("Cannot localize sizes: {0}", Ada.Exceptions.Exception_Message (E)); end; -- Convert the value as an integer here so that we can raise -- the Invalid_Conversion exception. declare Size : constant Long_Long_Integer := Util.Beans.Objects.To_Long_Long_Integer (Value); Val : Integer; Values : ASF.Utils.Object_Array (1 .. 1); Result : Ada.Strings.Unbounded.Unbounded_String; Unit : Util.Strings.Name_Access; begin if Size >= ONE_GB then Val := Integer ((Size + ONE_GB / 2) / ONE_GB); Unit := UNIT_GB'Access; elsif Size >= ONE_MB then Val := Integer ((Size + ONE_MB / 2) / ONE_MB); Unit := UNIT_MB'Access; elsif Size >= ONE_KB then Val := Integer ((Size + ONE_KB / 2) / ONE_KB); Unit := UNIT_KB'Access; else Val := Integer (Size); Unit := UNIT_B'Access; end if; Values (1) := Util.Beans.Objects.To_Object (Val); ASF.Utils.Formats.Format (Bundle.Get (Unit.all), Values, Result); return Ada.Strings.Unbounded.To_String (Result); end; exception when E : others => raise ASF.Converters.Invalid_Conversion with Ada.Exceptions.Exception_Message (E); end To_String; -- ------------------------------ -- Convert the date string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- ------------------------------ function To_Object (Convert : in Size_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Convert, Context, Value); begin Component.Log_Error ("Conversion of string to a size is not implemented"); raise ASF.Converters.Invalid_Conversion with "Not implemented"; return Util.Beans.Objects.Null_Object; end To_Object; end ASF.Converters.Sizes;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6b8b6cc10908bd368283f6468d7f267f7128bf88
src/wiki-filters.ads
src/wiki-filters.ads
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- 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 Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt> -- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations -- and it forwards the different calls to a next wiki document instance. A filter can do some -- operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type -- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- package Wiki.Filters is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type); -- 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 Filter_Type; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Filter_Type; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Filter_Type; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Filter_Type; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. procedure Finish (Document : in out Filter_Type); private type Filter_Type is new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- 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 Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt> -- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations -- and it forwards the different calls to a next wiki document instance. A filter can do some -- operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type -- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- package Wiki.Filters is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type); -- 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 Filter_Type; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Document : in out Filter_Type; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Document : in out Filter_Type; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Filter_Type; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. procedure Finish (Document : in out Filter_Type); private type Filter_Type is new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; end Wiki.Filters;
Update the Add_Link and Add_Image operations for the new implementation
Update the Add_Link and Add_Image operations for the new implementation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
eeee5689743593859e456d4152db06ff6583f09b
src/wiki-helpers.ads
src/wiki-helpers.ads
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; package Wiki.Helpers is pragma Preelaborate; LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#); CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#); HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a line terminator. function Is_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wiki.Strings.WString) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; package Wiki.Helpers is pragma Preelaborate; LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#); CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#); HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a line terminator. function Is_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wiki.Strings.WString) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; -- Get the dimension represented by the string. The string has one of the following -- formats: -- original -> Width, Height := Natural'Last -- default -> Width := 800, Height := 0 -- upright -> Width := 800, Height := 0 -- <width>px -> Width := <width>, Height := 0 -- x<height>px -> Width := 0, Height := <height> -- <width>x<height>px -> Width := <width>, Height := <height> procedure Get_Sizes (Dimension : in Wiki.Strings.WString; Width : out Natural; Height : out Natural); end Wiki.Helpers;
Declare the Get_Sizes procedure
Declare the Get_Sizes procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
309cd17177d2a3aeb15156b196aa3b68f781d621
src/el-variables-default.adb
src/el-variables-default.adb
----------------------------------------------------------------------- -- EL.Variables -- Default Variable Mapper -- 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 EL.Expressions; package body EL.Variables.Default is overriding procedure Bind (Mapper : in out Default_Variable_Mapper; Name : in String; Value : in EL.Objects.Object) is Expr : constant EL.Expressions.Value_Expression := EL.Expressions.Create_ValueExpression (Value); begin Mapper.Map.Include (Key => To_Unbounded_String (Name), New_Item => EL.Expressions.Expression (Expr)); end Bind; overriding function Get_Variable (Mapper : Default_Variable_Mapper; Name : Unbounded_String) return EL.Expressions.Expression is C : constant Variable_Maps.Cursor := Mapper.Map.Find (Name); begin if not Variable_Maps.Has_Element (C) then if Mapper.Next_Mapper /= null then return Mapper.Next_Mapper.Get_Variable (Name); end if; -- Avoid raising an exception if we can't resolve a variable. -- Instead, return a null expression. This speeds up the resolution and -- creation of Ada bean in ASF framework (cost of exception is high compared to this). return E : EL.Expressions.Expression; end if; return Variable_Maps.Element (C); end Get_Variable; overriding procedure Set_Variable (Mapper : in out Default_Variable_Mapper; Name : in Unbounded_String; Value : in EL.Expressions.Expression) is begin Mapper.Map.Include (Key => Name, New_Item => Value); end Set_Variable; -- ------------------------------ -- Set the next variable mapper that will be used to resolve a variable if -- the current variable mapper does not find a variable. -- ------------------------------ procedure Set_Next_Variable_Mapper (Mapper : in out Default_Variable_Mapper; Next_Mapper : in Variable_Mapper_Access) is begin Mapper.Next_Mapper := Next_Mapper; end Set_Next_Variable_Mapper; end EL.Variables.Default;
----------------------------------------------------------------------- -- EL.Variables -- Default Variable Mapper -- 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 EL.Expressions; package body EL.Variables.Default is overriding procedure Bind (Mapper : in out Default_Variable_Mapper; Name : in String; Value : in EL.Objects.Object) is Expr : constant EL.Expressions.Value_Expression := EL.Expressions.Create_ValueExpression (Value); begin Mapper.Map.Include (Key => To_Unbounded_String (Name), New_Item => EL.Expressions.Expression (Expr)); end Bind; overriding function Get_Variable (Mapper : Default_Variable_Mapper; Name : Unbounded_String) return EL.Expressions.Expression is C : constant Variable_Maps.Cursor := Mapper.Map.Find (Name); begin if not Variable_Maps.Has_Element (C) then if Mapper.Next_Mapper /= null then return Mapper.Next_Mapper.all.Get_Variable (Name); end if; -- Avoid raising an exception if we can't resolve a variable. -- Instead, return a null expression. This speeds up the resolution and -- creation of Ada bean in ASF framework (cost of exception is high compared to this). return E : EL.Expressions.Expression; end if; return Variable_Maps.Element (C); end Get_Variable; overriding procedure Set_Variable (Mapper : in out Default_Variable_Mapper; Name : in Unbounded_String; Value : in EL.Expressions.Expression) is begin Mapper.Map.Include (Key => Name, New_Item => Value); end Set_Variable; -- ------------------------------ -- Set the next variable mapper that will be used to resolve a variable if -- the current variable mapper does not find a variable. -- ------------------------------ procedure Set_Next_Variable_Mapper (Mapper : in out Default_Variable_Mapper; Next_Mapper : in Variable_Mapper_Access) is begin Mapper.Next_Mapper := Next_Mapper; end Set_Next_Variable_Mapper; end EL.Variables.Default;
Fix Issue 1:build failed with gcc 4.7
Fix Issue 1:build failed with gcc 4.7
Ada
apache-2.0
stcarrez/ada-el
6426597deed2cccab528f7d374358f18f07c31a5
src/security-oauth-clients.ads
src/security-oauth-clients.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- 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 Security.Permissions; -- 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 Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Permissions.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Access_Token; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is tagged private; -- 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); -- 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); -- 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); -- 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); -- OAuth 2.0 Section 4.1.1 Authorization Request -- 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; -- 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; -- OAuth 2.0 Section 4.1.2 Authorization Response -- 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; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Permissions.Principal with record Access_Id : String (1 .. Len); end record; type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; Request_URI : Ada.Strings.Unbounded.Unbounded_String; Protect : Ada.Strings.Unbounded.Unbounded_String; Key : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- 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 Security.Permissions; -- 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 Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is tagged private; -- 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); -- 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); -- 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); -- 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); -- OAuth 2.0 Section 4.1.1 Authorization Request -- 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; -- 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; -- OAuth 2.0 Section 4.1.2 Authorization Response -- 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; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; Request_URI : Ada.Strings.Unbounded.Unbounded_String; Protect : Ada.Strings.Unbounded.Unbounded_String; Key : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
Remove the Has_Role operation
Remove the Has_Role operation
Ada
apache-2.0
Letractively/ada-security
6b534b83a2e1f2ed317d27e9099b83a1e02d4046
src/ado-sql.ads
src/ado-sql.ads
----------------------------------------------------------------------- -- ADO SQL -- Basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ADO.Parameters; with ADO.Drivers.Dialects; -- Utilities for creating SQL queries and statements. package ADO.SQL is use Ada.Strings.Unbounded; -- -------------------- -- Buffer -- -------------------- -- The <b>Buffer</b> type allows to build easily an SQL statement. -- type Buffer is private; type Buffer_Access is access all Buffer; -- Clear the SQL buffer. procedure Clear (Target : in out Buffer); -- Append an SQL extract into the buffer. procedure Append (Target : in out Buffer; SQL : in String); -- Append a name in the buffer and escape that -- name if this is a reserved keyword. procedure Append_Name (Target : in out Buffer; Name : in String); -- Append a string value in the buffer and -- escape any special character if necessary. procedure Append_Value (Target : in out Buffer; Value : in String); -- Append a string value in the buffer and -- escape any special character if necessary. procedure Append_Value (Target : in out Buffer; Value : in Unbounded_String); -- Append the integer value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Long_Integer); -- Append the integer value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Integer); -- Append the identifier value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Identifier); -- Get the SQL string that was accumulated in the buffer. function To_String (From : in Buffer) return String; -- -------------------- -- Query -- -------------------- -- The <b>Query</b> type contains the elements for building and -- executing the request. This includes: -- <ul> -- <li>The SQL request (full request or a fragment)</li> -- <li>The SQL request parameters </li> -- <li>An SQL filter condition</li> -- </ul> -- type Query is new ADO.Parameters.List with record SQL : Buffer; Filter : Buffer; Join : Buffer; end record; type Query_Access is access all Query'Class; -- Clear the query object. overriding procedure Clear (Target : in out Query); -- Set the SQL dialect description object. procedure Set_Dialect (Target : in out Query; D : in ADO.Drivers.Dialects.Dialect_Access); procedure Set_Filter (Target : in out Query; Filter : in String); function Has_Filter (Source : in Query) return Boolean; function Get_Filter (Source : in Query) return String; -- Set the join condition. procedure Set_Join (Target : in out Query; Join : in String); -- Returns true if there is a join condition function Has_Join (Source : in Query) return Boolean; -- Get the join condition function Get_Join (Source : in Query) return String; -- Set the parameters from another parameter list. -- If the parameter list is a query object, also copy the filter part. procedure Set_Parameters (Params : in out Query; From : in ADO.Parameters.Abstract_List'Class); -- Expand the parameters into the query and return the expanded SQL query. function Expand (Source : in Query) return String; -- -------------------- -- Update Query -- -------------------- -- The <b>Update_Query</b> provides additional helper functions to construct -- and <i>insert</i> or an <i>update</i> statement. type Update_Query is new Query with private; type Update_Query_Access is access all Update_Query'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Target : in out Update_Query; D : in ADO.Drivers.Dialects.Dialect_Access); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Boolean); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Integer); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Long_Long_Integer); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Identifier); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Entity_Type); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Ada.Calendar.Time); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in String); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Unbounded_String); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in ADO.Blob_Ref); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to NULL. procedure Save_Null_Field (Update : in out Update_Query; Name : in String); -- Check if the update/insert query has some fields to update. function Has_Save_Fields (Update : in Update_Query) return Boolean; procedure Set_Insert_Mode (Update : in out Update_Query); procedure Append_Fields (Update : in out Update_Query; Mode : in Boolean := False); private type Buffer is new ADO.Parameters.List with record Buf : Unbounded_String; end record; type Update_Query is new Query with record Pos : Natural := 0; Set_Fields : Buffer; Fields : Buffer; Is_Update_Stmt : Boolean := True; end record; procedure Add_Field (Update : in out Update_Query'Class; Name : in String); end ADO.SQL;
----------------------------------------------------------------------- -- ADO SQL -- Basic SQL Generation -- Copyright (C) 2010, 2011, 2012, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ADO.Parameters; with ADO.Drivers.Dialects; -- Utilities for creating SQL queries and statements. package ADO.SQL is use Ada.Strings.Unbounded; -- -------------------- -- Buffer -- -------------------- -- The <b>Buffer</b> type allows to build easily an SQL statement. -- type Buffer is private; type Buffer_Access is access all Buffer; -- Clear the SQL buffer. procedure Clear (Target : in out Buffer); -- Append an SQL extract into the buffer. procedure Append (Target : in out Buffer; SQL : in String); -- Append a name in the buffer and escape that -- name if this is a reserved keyword. procedure Append_Name (Target : in out Buffer; Name : in String); -- Append a string value in the buffer and -- escape any special character if necessary. procedure Append_Value (Target : in out Buffer; Value : in String); -- Append a string value in the buffer and -- escape any special character if necessary. procedure Append_Value (Target : in out Buffer; Value : in Unbounded_String); -- Append the integer value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Long_Integer); -- Append the integer value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Integer); -- Append the identifier value in the buffer. procedure Append_Value (Target : in out Buffer; Value : in Identifier); -- Get the SQL string that was accumulated in the buffer. function To_String (From : in Buffer) return String; -- -------------------- -- Query -- -------------------- -- The <b>Query</b> type contains the elements for building and -- executing the request. This includes: -- <ul> -- <li>The SQL request (full request or a fragment)</li> -- <li>The SQL request parameters </li> -- <li>An SQL filter condition</li> -- </ul> -- type Query is new ADO.Parameters.List with record SQL : Buffer; Filter : Buffer; Join : Buffer; end record; type Query_Access is access all Query'Class; -- Clear the query object. overriding procedure Clear (Target : in out Query); -- Set the SQL dialect description object. procedure Set_Dialect (Target : in out Query; D : in ADO.Drivers.Dialects.Dialect_Access); procedure Set_Filter (Target : in out Query; Filter : in String); function Has_Filter (Source : in Query) return Boolean; function Get_Filter (Source : in Query) return String; -- Set the join condition. procedure Set_Join (Target : in out Query; Join : in String); -- Returns true if there is a join condition function Has_Join (Source : in Query) return Boolean; -- Get the join condition function Get_Join (Source : in Query) return String; -- Set the parameters from another parameter list. -- If the parameter list is a query object, also copy the filter part. procedure Set_Parameters (Params : in out Query; From : in ADO.Parameters.Abstract_List'Class); -- Expand the parameters into the query and return the expanded SQL query. function Expand (Source : in Query) return String; -- -------------------- -- Update Query -- -------------------- -- The <b>Update_Query</b> provides additional helper functions to construct -- and <i>insert</i> or an <i>update</i> statement. type Update_Query is new Query with private; type Update_Query_Access is access all Update_Query'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Target : in out Update_Query; D : in ADO.Drivers.Dialects.Dialect_Access); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Boolean); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Integer); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Long_Long_Integer); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Long_Float); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Identifier); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Entity_Type); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Ada.Calendar.Time); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in String); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in Unbounded_String); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to the <b>Value</b>. procedure Save_Field (Update : in out Update_Query; Name : in String; Value : in ADO.Blob_Ref); -- Prepare the update/insert query to save the table field -- identified by <b>Name</b> and set it to NULL. procedure Save_Null_Field (Update : in out Update_Query; Name : in String); -- Check if the update/insert query has some fields to update. function Has_Save_Fields (Update : in Update_Query) return Boolean; procedure Set_Insert_Mode (Update : in out Update_Query); procedure Append_Fields (Update : in out Update_Query; Mode : in Boolean := False); private type Buffer is new ADO.Parameters.List with record Buf : Unbounded_String; end record; type Update_Query is new Query with record Pos : Natural := 0; Set_Fields : Buffer; Fields : Buffer; Is_Update_Stmt : Boolean := True; end record; procedure Add_Field (Update : in out Update_Query'Class; Name : in String); end ADO.SQL;
Declare a Save_Field procedure with a Long_Float type
Declare a Save_Field procedure with a Long_Float type
Ada
apache-2.0
stcarrez/ada-ado
0cbbb37f05a9c3edbe1f5b24c44ded6dad15366c
awa/regtests/awa-users-services-tests.adb
awa/regtests/awa-users-services-tests.adb
----------------------------------------------------------------------- -- users - User creation, password tests -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with AWA.Users.Module; with AWA.Users.Services.Tests.Helpers; package body AWA.Users.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User", 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.Services.Authenticate, Close_Session", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module", Test_Get_Module'Access); end Add_Tests; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Create_User (T : in out Test) is Principal : Helpers.Test_User; begin -- Create the user Helpers.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session must be created"); T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); t.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started"); T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Create_User; -- ------------------------------ -- Test logout of a user -- ------------------------------ procedure Test_Logout_User (T : in out Test) is Principal : Helpers.Test_User; begin -- Create the user Helpers.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); Helpers.Logout (Principal); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (False, "Verify_Session should report a non-existent session"); exception when Not_Found => null; end; begin Helpers.Logout (Principal); T.Assert (False, "Second logout should report a non-existent session"); exception when Not_Found => null; end; end Test_Logout_User; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type Ada.Calendar.Time; Principal : Helpers.Test_User; T1 : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin begin Principal.Email.Set_Email ("[email protected]"); Helpers.Login (Principal); T.Assert (False, "Login succeeded with an invalid user name"); exception when Not_Found => null; end; -- Create the user Helpers.Create_User (Principal); Helpers.Logout (Principal); Helpers.Login (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null"); T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); Util.Tests.Assert_Equals (T, T1, S1.Get_Start_Date.Value, "Invalid start date 3"); T.Assert (T2 >= S1.Get_Start_Date.Value, "Start date is invalid 1"); T.Assert (T1 <= S1.Get_Start_Date.Value + 1.0, "Start date is invalid 2"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Login_User; -- ------------------------------ -- Test password reset process -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is Principal : Helpers.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin -- Create the user Helpers.Create_User (Principal); Helpers.Logout (Principal); -- Start the lost password process. Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email); Helpers.Login (Principal); -- Get the access key to reset the password declare DB : ADO.Sessions.Session := Principal.Manager.Get_Session; Query : ADO.SQL.Query; Found : Boolean; begin -- Find the access key Query.Set_Filter ("user_id = ?"); Query.Bind_Param (1, Principal.User.Get_Id); Key.Find (DB, Query, Found); T.Assert (Found, "Access key for lost_password process not found"); Principal.Manager.Reset_Password (Key => Key.Get_Access_Key, Password => "newadmin", IpAddr => "192.168.1.2", User => Principal.User, Session => Principal.Session); -- Search the access key again, it must have been removed. Key.Find (DB, Query, Found); T.Assert (not Found, "The access key is still present in the database"); end; T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); Helpers.Logout (Principal); end Test_Reset_Password_User; -- ------------------------------ -- Test Get_User_Module operation -- ------------------------------ procedure Test_Get_Module (T : in out Test) is use type AWA.Users.Module.User_Module_Access; begin declare M : constant AWA.Users.Module.User_Module_Access := AWA.Users.Module.Get_User_Module; begin T.Assert (M /= null, "Get_User_Module returned null"); end; declare S : Util.Measures.Stamp; M : AWA.Users.Module.User_Module_Access; begin for I in 1 .. 1_000 loop M := AWA.Users.Module.Get_User_Module; end loop; Util.Measures.Report (S, "Get_User_Module (1000)"); T.Assert (M /= null, "Get_User_Module returned null"); end; end Test_Get_Module; end AWA.Users.Services.Tests;
----------------------------------------------------------------------- -- users - User creation, password tests -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with AWA.Users.Module; with AWA.Users.Services.Tests.Helpers; package body AWA.Users.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User", 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.Services.Authenticate, Close_Session", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module", Test_Get_Module'Access); end Add_Tests; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Create_User (T : in out Test) is Principal : Helpers.Test_User; begin -- Create the user Helpers.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session must be created"); T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); t.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started"); T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Create_User; -- ------------------------------ -- Test logout of a user -- ------------------------------ procedure Test_Logout_User (T : in out Test) is Principal : Helpers.Test_User; begin -- Create the user Helpers.Create_User (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); Helpers.Logout (Principal); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (False, "Verify_Session should report a non-existent session"); exception when Not_Found => null; end; begin Helpers.Logout (Principal); T.Assert (False, "Second logout should report a non-existent session"); exception when Not_Found => null; end; end Test_Logout_User; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type Ada.Calendar.Time; Principal : Helpers.Test_User; T1 : Ada.Calendar.Time; begin begin Principal.Email.Set_Email ("[email protected]"); Helpers.Login (Principal); T.Assert (False, "Login succeeded with an invalid user name"); exception when Not_Found => null; end; -- Create the user T1 := Ada.Calendar.Clock; Helpers.Create_User (Principal); Helpers.Logout (Principal); Helpers.Login (Principal); T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); -- Verify the user session declare S1 : Session_Ref; U1 : User_Ref; T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id, Session => S1, User => U1); T.Assert (not S1.Is_Null, "Null session returned by Verify_Session"); T.Assert (not U1.Is_Null, "Null user returned by Verify_Session"); T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null"); T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null"); Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value, S1.Get_Start_Date.Value, "Invalid start date"); T.Assert (S1.Get_Start_Date.Value >= T1, "Start date is invalid 1"); T.Assert (S1.Get_Start_Date.Value >= T2, "Start date is invalid 2"); T.Assert (S1.Get_Start_Date.Value <= T2 + 10.0, "Start date is invalid 3"); Principal.Manager.Close_Session (Principal.Session.Get_Id); end; end Test_Login_User; -- ------------------------------ -- Test password reset process -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is Principal : Helpers.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin -- Create the user Helpers.Create_User (Principal); Helpers.Logout (Principal); -- Start the lost password process. Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email); Helpers.Login (Principal); -- Get the access key to reset the password declare DB : ADO.Sessions.Session := Principal.Manager.Get_Session; Query : ADO.SQL.Query; Found : Boolean; begin -- Find the access key Query.Set_Filter ("user_id = ?"); Query.Bind_Param (1, Principal.User.Get_Id); Key.Find (DB, Query, Found); T.Assert (Found, "Access key for lost_password process not found"); Principal.Manager.Reset_Password (Key => Key.Get_Access_Key, Password => "newadmin", IpAddr => "192.168.1.2", User => Principal.User, Session => Principal.Session); -- Search the access key again, it must have been removed. Key.Find (DB, Query, Found); T.Assert (not Found, "The access key is still present in the database"); end; T.Assert (not Principal.User.Is_Null, "User is created"); T.Assert (Principal.User.Get_Id > 0, "User has an allocated key"); T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key"); T.Assert (not Principal.Session.Is_Null, "Session is not created"); Helpers.Logout (Principal); end Test_Reset_Password_User; -- ------------------------------ -- Test Get_User_Module operation -- ------------------------------ procedure Test_Get_Module (T : in out Test) is use type AWA.Users.Module.User_Module_Access; begin declare M : constant AWA.Users.Module.User_Module_Access := AWA.Users.Module.Get_User_Module; begin T.Assert (M /= null, "Get_User_Module returned null"); end; declare S : Util.Measures.Stamp; M : AWA.Users.Module.User_Module_Access; begin for I in 1 .. 1_000 loop M := AWA.Users.Module.Get_User_Module; end loop; Util.Measures.Report (S, "Get_User_Module (1000)"); T.Assert (M /= null, "Get_User_Module returned null"); end; end Test_Get_Module; end AWA.Users.Services.Tests;
Fix test check on dates
Fix test check on dates
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3deba4f1cb6cab70c92ed3b9926b18b8e1758b59
src/el-beans.ads
src/el-beans.ads
----------------------------------------------------------------------- -- EL.Beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package EL.Beans is -- Exception raised when the value identified by a name is not -- recognized. No_Value : exception; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return EL.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is interface and Readonly_Bean; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. function Get_Count (From : List_Bean) return Natural is abstract; -- Set the current row index. Valid row indexes start at 1. procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is abstract; -- Get the element at the current row index. function Get_Row (From : List_Bean) return EL.Objects.Object is abstract; end EL.Beans;
----------------------------------------------------------------------- -- EL.Beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package EL.Beans is -- Exception raised when the value identified by a name is not -- recognized. No_Value : exception; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is limited interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return EL.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is limited interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is limited interface and Readonly_Bean; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. function Get_Count (From : List_Bean) return Natural is abstract; -- Set the current row index. Valid row indexes start at 1. procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is abstract; -- Get the element at the current row index. function Get_Row (From : List_Bean) return EL.Objects.Object is abstract; end EL.Beans;
Make the interface limited to allow limited types to implement the bean interfaces.
Make the interface limited to allow limited types to implement the bean interfaces.
Ada
apache-2.0
stcarrez/ada-el
72c9e93daebbd45a0fabeba6975ae7ec05a9711d
awa/awaunit/awa-tests.adb
awa/awaunit/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with Util.Log.Loggers; with ASF.Tests; with AWA.Applications.Factory; with AWA.Tests.Helpers.Users; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; -- ------------------------------ -- Cleanup after the test execution. -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is pragma Unreferenced (T); begin AWA.Tests.Helpers.Users.Tear_Down; end Tear_Down; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Application.Close; Free (Application); end if; ASF.Tests.Finish (Status); end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is pragma Unreferenced (Add_Modules); use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new Test_Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Test_Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access); App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Test_Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access); end Initialize_Filters; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with ASF.Tests; with Servlet.Tests; with AWA.Applications.Factory; with AWA.Tests.Helpers.Users; package body AWA.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests"); protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin Servlet.Tests.Set_Context (Application.all'Access); end Set_Up; -- ------------------------------ -- Cleanup after the test execution. -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is pragma Unreferenced (T); begin AWA.Tests.Helpers.Users.Tear_Down; end Tear_Down; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Application.Close; Free (Application); end if; ASF.Tests.Finish (Status); end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is pragma Unreferenced (Add_Modules); use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new Test_Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin Servlet.Tests.Set_Context (Application.all'Access); end Set_Application_Context; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Test_Application) is begin Log.Info ("Initializing application servlets..."); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Servlet (Name => "ajax", Server => App.Ajax'Unchecked_Access); App.Add_Servlet (Name => "measures", Server => App.Measures'Unchecked_Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Test_Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Dump'Unchecked_Access); App.Add_Filter (Name => "measures", Filter => App.Measures'Unchecked_Access); App.Add_Filter (Name => "service", Filter => App.Service_Filter'Unchecked_Access); end Initialize_Filters; end AWA.Tests;
Update to use the Servlet package instead of ASF.Servlet
Update to use the Servlet package instead of ASF.Servlet
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e4f9b5ff41115905ee8ba0ea59d6d167078caf6b
src/orka/implementation/orka-loops.adb
src/orka/implementation/orka-loops.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 System.Multiprocessors.Dispatching_Domains; with Ada.Unchecked_Conversion; with Ada.Unchecked_Deallocation; with Ada.Exceptions; with Orka.Futures; with Orka.Loggers; with Orka.Logging; with Orka.Simulation_Jobs; package body Orka.Loops is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Game_Loop); procedure Free is new Ada.Unchecked_Deallocation (Behaviors.Behavior_Array, Behaviors.Behavior_Array_Access); function "<" (Left, Right : Behaviors.Behavior_Ptr) return Boolean is function Convert is new Ada.Unchecked_Conversion (Source => System.Address, Target => Long_Integer); begin return Convert (Left.all'Address) < Convert (Right.all'Address); end "<"; protected body Handler is procedure Stop is begin Stop_Flag := True; end Stop; procedure Set_Frame_Limit (Value : Time_Span) is begin Limit := Value; end Set_Frame_Limit; function Frame_Limit return Time_Span is (Limit); procedure Enable_Limit (Enable : Boolean) is begin Limit_Flag := Enable; end Enable_Limit; function Limit_Enabled return Boolean is (Limit_Flag); function Should_Stop return Boolean is (Stop_Flag); end Handler; protected body Scene is procedure Add (Object : Behaviors.Behavior_Ptr) is begin Behaviors_Set.Insert (Object); Modified_Flag := True; end Add; procedure Remove (Object : Behaviors.Behavior_Ptr) is begin Behaviors_Set.Delete (Object); Modified_Flag := True; end Remove; procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) is pragma Assert (Modified); Index : Positive := 1; Count : constant Positive := Positive (Behaviors_Set.Length); begin Free (Target); Target := new Behaviors.Behavior_Array'(1 .. Count => Behaviors.Null_Behavior); -- Copy the elements from the set to the array -- for faster iteration by the game loop for Element of Behaviors_Set loop Target (Index) := Element; Index := Index + 1; end loop; Modified_Flag := False; end Replace_Array; function Modified return Boolean is (Modified_Flag); procedure Set_Camera (Camera : Cameras.Camera_Ptr) is begin Scene_Camera := Camera; end Set_Camera; function Camera return Cameras.Camera_Ptr is (Scene_Camera); end Scene; package SJ renames Simulation_Jobs; procedure Stop_Loop is begin Handler.Stop; end Stop_Loop; procedure Run_Game_Loop (Fence : not null access SJ.Fences.Buffer_Fence) is Previous_Time : Time := Clock; Next_Time : Time := Previous_Time; Lag : Time_Span := Time_Span_Zero; Scene_Array : not null Behaviors.Behavior_Array_Access := Behaviors.Empty_Behavior_Array; Batch_Length : constant := 10; One_Second : constant Time_Span := Seconds (1); Frame_Counter : Natural := 0; Exceeded_Frame_Counter : Natural := 0; Clock_FPS_Start : Time := Clock; Stat_Sum : Time_Span := Time_Span_Zero; Stat_Min : Duration := To_Duration (One_Second); Stat_Max : Duration := To_Duration (-One_Second); begin Scene.Replace_Array (Scene_Array); Messages.Log (Debug, "Simulation tick resolution: " & Trim (Image (Tick))); -- Based on http://gameprogrammingpatterns.com/game-loop.html loop declare Current_Time : constant Time := Clock; Elapsed : constant Time_Span := Current_Time - Previous_Time; begin Previous_Time := Current_Time; Lag := Lag + Elapsed; exit when Handler.Should_Stop; declare Iterations : constant Natural := Lag / Time_Step; begin Lag := Lag - Iterations * Time_Step; Scene.Camera.Update (To_Duration (Lag)); declare Fixed_Update_Job : constant Jobs.Job_Ptr := Jobs.Parallelize (SJ.Create_Fixed_Update_Job (Scene_Array, Time_Step, Iterations), SJ.Clone_Fixed_Update_Job'Access, Scene_Array'Length, Batch_Length); Finished_Job : constant Jobs.Job_Ptr := SJ.Create_Finished_Job (Scene_Array, Time_Step, Scene.Camera.View_Position, Batch_Length); Render_Scene_Job : constant Jobs.Job_Ptr := SJ.Create_Scene_Render_Job (Render, Scene_Array, Scene.Camera); Render_Start_Job : constant Jobs.Job_Ptr := SJ.Create_Start_Render_Job (Fence, Window); Render_Finish_Job : constant Jobs.Job_Ptr := SJ.Create_Finish_Render_Job (Fence, Window, Stop_Loop'Unrestricted_Access); Handle : Futures.Pointers.Mutable_Pointer; Status : Futures.Status; begin Orka.Jobs.Chain ((Render_Start_Job, Fixed_Update_Job, Finished_Job, Render_Scene_Job, Render_Finish_Job)); Job_Manager.Queue.Enqueue (Render_Start_Job, Handle); declare Frame_Future : constant Orka.Futures.Future_Access := Handle.Get.Value; begin select Frame_Future.Wait_Until_Done (Status); or delay until Current_Time + Maximum_Frame_Time; raise Program_Error with "Maximum frame time of " & Trim (Image (Maximum_Frame_Time)) & " exceeded"; end select; end; end; end; if Scene.Modified then Scene.Replace_Array (Scene_Array); end if; declare Total_Elapsed : constant Time_Span := Clock - Clock_FPS_Start; Limit_Exceeded : constant Time_Span := Elapsed - Handler.Frame_Limit; begin Frame_Counter := Frame_Counter + 1; if Limit_Exceeded > Time_Span_Zero then Stat_Sum := Stat_Sum + Limit_Exceeded; Stat_Min := Duration'Min (Stat_Min, To_Duration (Limit_Exceeded)); Stat_Max := Duration'Max (Stat_Max, To_Duration (Limit_Exceeded)); Exceeded_Frame_Counter := Exceeded_Frame_Counter + 1; end if; if Total_Elapsed > One_Second then declare FPS : constant Duration := Duration (Frame_Counter) / To_Duration (Total_Elapsed); begin Messages.Log (Debug, "FPS: " & Trim (FPS'Image)); end; if Exceeded_Frame_Counter > 0 then declare Avg : constant Time_Span := Stat_Sum / Exceeded_Frame_Counter; begin Messages.Log (Debug, "Frame time limit (" & Trim (Image (Handler.Frame_Limit)) & ") exceeded " & Trim (Exceeded_Frame_Counter'Image) & " times by:"); Messages.Log (Debug, " avg: " & Image (Avg)); Messages.Log (Debug, " min: " & Image (To_Time_Span (Stat_Min))); Messages.Log (Debug, " max: " & Image (To_Time_Span (Stat_Max))); end; end if; Clock_FPS_Start := Clock; Frame_Counter := 0; Exceeded_Frame_Counter := 0; Stat_Sum := Time_Span_Zero; Stat_Min := To_Duration (One_Second); Stat_Max := To_Duration (Time_Span_Zero); end if; end; if Handler.Limit_Enabled then -- Do not sleep if Next_Time fell behind more than one frame -- due to high workload (FPS dropping below limit), otherwise -- the FPS will be exceeded during a subsequent low workload -- until Next_Time has catched up if Next_Time < Current_Time - Handler.Frame_Limit then Next_Time := Current_Time; else Next_Time := Next_Time + Handler.Frame_Limit; delay until Next_Time; end if; end if; end; end loop; Job_Manager.Shutdown; exception when others => Job_Manager.Shutdown; raise; end Run_Game_Loop; procedure Run_Loop is Fence : aliased SJ.Fences.Buffer_Fence := SJ.Fences.Create_Buffer_Fence; begin declare -- Create a separate task for the game loop. The current task -- will be used to dequeue and execute GPU jobs. task Simulation; use Ada.Exceptions; task body Simulation is begin System.Multiprocessors.Dispatching_Domains.Set_CPU (1); Run_Game_Loop (Fence'Unchecked_Access); exception when Error : others => Messages.Log (Loggers.Error, Exception_Information (Error)); end Simulation; begin System.Multiprocessors.Dispatching_Domains.Set_CPU (1); -- Execute GPU jobs in the current task Job_Manager.Execute_GPU_Jobs; end; end Run_Loop; end Orka.Loops;
-- 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 System.Multiprocessors.Dispatching_Domains; with Ada.Unchecked_Conversion; with Ada.Unchecked_Deallocation; with Ada.Exceptions; with Orka.Futures; with Orka.Loggers; with Orka.Logging; with Orka.Simulation_Jobs; package body Orka.Loops is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Game_Loop); procedure Free is new Ada.Unchecked_Deallocation (Behaviors.Behavior_Array, Behaviors.Behavior_Array_Access); function "<" (Left, Right : Behaviors.Behavior_Ptr) return Boolean is function Convert is new Ada.Unchecked_Conversion (Source => System.Address, Target => Long_Integer); begin return Convert (Left.all'Address) < Convert (Right.all'Address); end "<"; protected body Handler is procedure Stop is begin Stop_Flag := True; end Stop; procedure Set_Frame_Limit (Value : Time_Span) is begin Limit := Value; end Set_Frame_Limit; function Frame_Limit return Time_Span is (Limit); procedure Enable_Limit (Enable : Boolean) is begin Limit_Flag := Enable; end Enable_Limit; function Limit_Enabled return Boolean is (Limit_Flag); function Should_Stop return Boolean is (Stop_Flag); end Handler; protected body Scene is procedure Add (Object : Behaviors.Behavior_Ptr) is begin Behaviors_Set.Insert (Object); Modified_Flag := True; end Add; procedure Remove (Object : Behaviors.Behavior_Ptr) is begin Behaviors_Set.Delete (Object); Modified_Flag := True; end Remove; procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) is pragma Assert (Modified); Index : Positive := 1; Count : constant Positive := Positive (Behaviors_Set.Length); begin Free (Target); Target := new Behaviors.Behavior_Array'(1 .. Count => Behaviors.Null_Behavior); -- Copy the elements from the set to the array -- for faster iteration by the game loop for Element of Behaviors_Set loop Target (Index) := Element; Index := Index + 1; end loop; Modified_Flag := False; end Replace_Array; function Modified return Boolean is (Modified_Flag); procedure Set_Camera (Camera : Cameras.Camera_Ptr) is begin Scene_Camera := Camera; end Set_Camera; function Camera return Cameras.Camera_Ptr is (Scene_Camera); end Scene; package SJ renames Simulation_Jobs; procedure Stop_Loop is begin Handler.Stop; end Stop_Loop; procedure Run_Game_Loop (Fence : not null access SJ.Fences.Buffer_Fence) is Previous_Time : Time := Clock; Next_Time : Time := Previous_Time; Lag : Time_Span := Time_Span_Zero; Scene_Array : not null Behaviors.Behavior_Array_Access := Behaviors.Empty_Behavior_Array; Batch_Length : constant := 10; One_Second : constant Time_Span := Seconds (1); Frame_Counter : Natural := 0; Exceeded_Frame_Counter : Natural := 0; Clock_FPS_Start : Time := Clock; Stat_Sum : Time_Span := Time_Span_Zero; Stat_Min : Duration := To_Duration (One_Second); Stat_Max : Duration := To_Duration (-One_Second); begin Scene.Replace_Array (Scene_Array); Messages.Log (Debug, "Simulation tick resolution: " & Trim (Image (Tick))); -- Based on http://gameprogrammingpatterns.com/game-loop.html loop declare Current_Time : constant Time := Clock; Elapsed : constant Time_Span := Current_Time - Previous_Time; begin Previous_Time := Current_Time; Lag := Lag + Elapsed; exit when Handler.Should_Stop; declare Iterations : constant Natural := Lag / Time_Step; begin Lag := Lag - Iterations * Time_Step; Scene.Camera.Update (To_Duration (Lag)); declare Fixed_Update_Job : constant Jobs.Job_Ptr := Jobs.Parallelize (SJ.Create_Fixed_Update_Job (Scene_Array, Time_Step, Iterations), SJ.Clone_Fixed_Update_Job'Access, Scene_Array'Length, Batch_Length); Finished_Job : constant Jobs.Job_Ptr := SJ.Create_Finished_Job (Scene_Array, Time_Step, Scene.Camera.View_Position, Batch_Length); Render_Scene_Job : constant Jobs.Job_Ptr := SJ.Create_Scene_Render_Job (Render, Scene_Array, Scene.Camera); Render_Start_Job : constant Jobs.Job_Ptr := SJ.Create_Start_Render_Job (Fence, Window); Render_Finish_Job : constant Jobs.Job_Ptr := SJ.Create_Finish_Render_Job (Fence, Window, Stop_Loop'Unrestricted_Access); Handle : Futures.Pointers.Mutable_Pointer; Status : Futures.Status; begin Orka.Jobs.Chain ((Render_Start_Job, Fixed_Update_Job, Finished_Job, Render_Scene_Job, Render_Finish_Job)); Job_Manager.Queue.Enqueue (Render_Start_Job, Handle); declare Frame_Future : constant Orka.Futures.Future_Access := Handle.Get.Value; begin select Frame_Future.Wait_Until_Done (Status); or delay until Current_Time + Maximum_Frame_Time; raise Program_Error with "Maximum frame time of " & Trim (Image (Maximum_Frame_Time)) & " exceeded"; end select; end; end; end; if Scene.Modified then Scene.Replace_Array (Scene_Array); end if; declare Total_Elapsed : constant Time_Span := Clock - Clock_FPS_Start; Limit_Exceeded : constant Time_Span := Elapsed - Handler.Frame_Limit; begin Frame_Counter := Frame_Counter + 1; if Limit_Exceeded > Time_Span_Zero then Stat_Sum := Stat_Sum + Limit_Exceeded; Stat_Min := Duration'Min (Stat_Min, To_Duration (Limit_Exceeded)); Stat_Max := Duration'Max (Stat_Max, To_Duration (Limit_Exceeded)); Exceeded_Frame_Counter := Exceeded_Frame_Counter + 1; end if; if Total_Elapsed > One_Second then declare Frame_Time : constant Time_Span := Total_Elapsed / Frame_Counter; FPS : constant Integer := Integer (1.0 / To_Duration (Frame_Time)); begin Messages.Log (Debug, Trim (FPS'Image) & " FPS, frame time: " & Trim (Image (Frame_Time))); end; if Exceeded_Frame_Counter > 0 then declare Stat_Avg : constant Time_Span := Stat_Sum / Exceeded_Frame_Counter; begin Messages.Log (Debug, " deadline missed: " & Trim (Exceeded_Frame_Counter'Image) & " (limit is " & Trim (Image (Handler.Frame_Limit)) & ")"); Messages.Log (Debug, " avg/min/max: " & Image (Stat_Avg) & Image (To_Time_Span (Stat_Min)) & Image (To_Time_Span (Stat_Max))); end; end if; Clock_FPS_Start := Clock; Frame_Counter := 0; Exceeded_Frame_Counter := 0; Stat_Sum := Time_Span_Zero; Stat_Min := To_Duration (One_Second); Stat_Max := To_Duration (Time_Span_Zero); end if; end; if Handler.Limit_Enabled then -- Do not sleep if Next_Time fell behind more than one frame -- due to high workload (FPS dropping below limit), otherwise -- the FPS will be exceeded during a subsequent low workload -- until Next_Time has catched up if Next_Time < Current_Time - Handler.Frame_Limit then Next_Time := Current_Time; else Next_Time := Next_Time + Handler.Frame_Limit; delay until Next_Time; end if; end if; end; end loop; Job_Manager.Shutdown; exception when others => Job_Manager.Shutdown; raise; end Run_Game_Loop; procedure Run_Loop is Fence : aliased SJ.Fences.Buffer_Fence := SJ.Fences.Create_Buffer_Fence; begin declare -- Create a separate task for the game loop. The current task -- will be used to dequeue and execute GPU jobs. task Simulation; use Ada.Exceptions; task body Simulation is begin System.Multiprocessors.Dispatching_Domains.Set_CPU (1); Run_Game_Loop (Fence'Unchecked_Access); exception when Error : others => Messages.Log (Loggers.Error, Exception_Information (Error)); end Simulation; begin System.Multiprocessors.Dispatching_Domains.Set_CPU (1); -- Execute GPU jobs in the current task Job_Manager.Execute_GPU_Jobs; end; end Run_Loop; end Orka.Loops;
Change formatting of FPS and frame time in log messages
orka: Change formatting of FPS and frame time in log messages Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
8ef83e4e5595d3baa88477b56dd9d9f0ba30d0a6
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_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 attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String); -- 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); -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- 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_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 attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String); -- 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); -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- 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;
Remove Write_Entity and Write_Attribute on Nullable_String
Remove Write_Entity and Write_Attribute on Nullable_String
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
376522f5dc67dc125a6695a75d2ab883e1f4c24c
src/sys/streams/util-streams-texts.ads
src/sys/streams/util-streams-texts.ads
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Streams.Buffered; with Ada.Calendar; with GNAT.Calendar.Time_IO; -- == Texts == -- The <tt>Util.Streams.Texts</tt> package implements text oriented input and output streams. -- The <tt>Print_Stream</tt> type extends the <tt>Output_Buffer_Stream</tt> to allow writing -- text content. -- -- The <tt>Reader_Stream</tt> package extends the <tt>Input_Buffer_Stream</tt> and allows to -- read text content. package Util.Streams.Texts is -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Buffered.Output_Buffer_Stream with private; type Print_Stream_Access is access all Print_Stream'Class; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access); -- Write a raw character on the stream. procedure Write (Stream : in out Print_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 Print_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer); -- Write a date on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date); -- Get the output stream content as a string. function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String; -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character); -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character); -- ----------------------- -- Reader stream -- ----------------------- -- The <b>Reader_Stream</b> is an input stream which provides helper methods -- for reading text streams. type Reader_Stream is new Buffered.Input_Buffer_Stream with private; type Reader_Stream_Access is access all Reader_Stream'Class; -- Initialize the reader to read the input from the input stream given in <b>From</b>. procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access); -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False); private type Print_Stream is new Buffered.Output_Buffer_Stream with null record; type Reader_Stream is new Buffered.Input_Buffer_Stream with null record; end Util.Streams.Texts;
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Streams.Buffered; with Ada.Calendar; with GNAT.Calendar.Time_IO; -- == Texts == -- The <tt>Util.Streams.Texts</tt> package implements text oriented input and output streams. -- The <tt>Print_Stream</tt> type extends the <tt>Output_Buffer_Stream</tt> to allow writing -- text content. -- -- The <tt>Reader_Stream</tt> package extends the <tt>Input_Buffer_Stream</tt> and allows to -- read text content. package Util.Streams.Texts is -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Buffered.Output_Buffer_Stream with private; type Print_Stream_Access is access all Print_Stream'Class; procedure Initialize (Stream : in out Print_Stream; To : access Output_Stream'Class); -- Write a raw character on the stream. procedure Write (Stream : in out Print_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 Print_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer); -- Write a date on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date); -- Get the output stream content as a string. function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String; -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character); -- Write a character on the stream. procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character); -- ----------------------- -- Reader stream -- ----------------------- -- The <b>Reader_Stream</b> is an input stream which provides helper methods -- for reading text streams. type Reader_Stream is new Buffered.Input_Buffer_Stream with private; type Reader_Stream_Access is access all Reader_Stream'Class; -- Initialize the reader to read the input from the input stream given in <b>From</b>. procedure Initialize (Stream : in out Reader_Stream; From : access Input_Stream'Class); -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False); private type Print_Stream is new Buffered.Output_Buffer_Stream with null record; type Reader_Stream is new Buffered.Input_Buffer_Stream with null record; end Util.Streams.Texts;
Use anonymous access type for the input and output streams
Use anonymous access type for the input and output streams
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
cfd35820652be0138d97f01d152f5651efb70bf4
mat/src/mat-targets-readers.adb
mat/src/mat-targets-readers.adb
----------------------------------------------------------------------- -- mat-targets-readers - Definition and Analysis of process start 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; package body MAT.Targets.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE)); procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref) is begin MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; overriding procedure Dispatch (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is begin case Id is when MSG_BEGIN => null; when MSG_END => null; when others => null; end case; end Dispatch; -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access) is begin Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Reader (Reader.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; end MAT.Targets.Readers;
----------------------------------------------------------------------- -- mat-targets-readers - Definition and Analysis of process start 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; package body MAT.Targets.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Readers"); MSG_BEGIN : constant MAT.Events.Internal_Reference := 0; MSG_END : constant MAT.Events.Internal_Reference := 1; M_PID : constant MAT.Events.Internal_Reference := 1; M_EXE : constant MAT.Events.Internal_Reference := 2; PID_NAME : aliased constant String := "pid"; EXE_NAME : aliased constant String := "exe"; Process_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => PID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_PID), 2 => (Name => EXE_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_EXE)); procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref) is begin MAT.Memory.Targets.Initialize (Memory => For_Servant.Process.Memory, Reader => For_Servant.Reader.all); end Create_Process; overriding procedure Dispatch (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is begin case Id is when MSG_BEGIN => null; when MSG_END => null; when others => null; end case; end Dispatch; -- ------------------------------ -- Register the reader to extract and analyze process events. -- ------------------------------ procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access) is begin Reader.Reader := Into'Unchecked_Access; Into.Register_Reader (Reader.all'Access, "begin", MSG_BEGIN, Process_Attributes'Access); Into.Register_Reader (Reader.all'Access, "end", MSG_END, Process_Attributes'Access); end Register; -- ------------------------------ -- Initialize the target object to prepare for reading process events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is Process_Reader : constant Process_Reader_Access := new Process_Servant; begin Process_Reader.Target := Target'Unrestricted_Access; Register (Reader, Process_Reader); end Initialize; end MAT.Targets.Readers;
Implement the Initialize procedure
Implement the Initialize procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
aa88a6e1aafab9217bd99762508e0d141dbf1fe8
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- 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.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; overriding procedure Add_File (Into : in out File_Queue; Path : in String; Element : in File) is begin Into.Queue.Enqueue (Element); end Add_File; overriding procedure Add_Directory (Into : in out File_Queue; Path : in String; Name : in String) is begin Into.Directories.Append (Util.Files.Compose (Path, Name)); end Add_Directory; procedure Compute_Sha1 (Path : in String; Into : in out File) is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; File : Ada.Streams.Stream_IO.File_Type; Name : constant String := Path & "/" & To_String (Into.Name); Last : Ada.Streams.Stream_Element_Offset; Buf : Ada.Streams.Stream_Element_Array (0 .. 32_767); Ctx : Util.Encoders.SHA1.Context; begin Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Name); loop Ada.Streams.Stream_IO.Read (File, Buf, Last); Util.Encoders.SHA1.Update (Ctx, Buf (Buf'First .. Last)); exit when Last /= Buf'Last; end loop; Ada.Streams.Stream_IO.Close (File); Util.Encoders.SHA1.Finish (Ctx, Into.SHA1); end Compute_Sha1; procedure Iterate_Files (Path : in String; Dir : in out Directory; Depth : in Natural; Update : access procedure (P : in String; F : in out File)) is use Ada.Strings.Unbounded; Iter : File_Vectors.Cursor := Dir.Files.First; procedure Iterate_File (Item : in out File) is begin Update (Path, Item); end Iterate_File; procedure Iterate_Child (Item : in out Directory) is begin Iterate_Files (Path & "/" & To_String (Item.Name), Item, Depth - 1, Update); end Iterate_Child; begin while File_Vectors.Has_Element (Iter) loop Dir.Files.Update_Element (Iter, Iterate_File'Access); File_Vectors.Next (Iter); end loop; if Depth > 0 and then Dir.Children /= null then declare Dir_Iter : Directory_Vectors.Cursor := Dir.Children.First; begin while Directory_Vectors.Has_Element (Dir_Iter) loop Dir.Children.Update_Element (Dir_Iter, Iterate_Child'Access); Directory_Vectors.Next (Dir_Iter); end loop; end; end if; end Iterate_Files; procedure Scan_Files (Path : in String; Into : in out Directory) is Iter : File_Vectors.Cursor := Into.Files.First; procedure Compute_Sha1 (Item : in out File) is begin Compute_Sha1 (Path, Item); end Compute_Sha1; begin while File_Vectors.Has_Element (Iter) loop Into.Files.Update_Element (Iter, Compute_Sha1'Access); File_Vectors.Next (Iter); end loop; end Scan_Files; procedure Scan_Children (Path : in String; Into : in out Directory) is procedure Update (Dir : in out Directory) is use Ada.Strings.Unbounded; use type Ada.Directories.File_Size; begin Scan (Path & "/" & To_String (Dir.Name), Dir); Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files; Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size; Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs; end Update; begin if Into.Children /= null then declare Iter : Directory_Vectors.Cursor := Into.Children.First; begin while Directory_Vectors.Has_Element (Iter) loop Into.Children.Update_Element (Iter, Update'Access); Directory_Vectors.Next (Iter); end loop; end; end if; end Scan_Children; procedure Scan (Path : in String; Into : in out Directory) is use Ada.Directories; Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; New_File : File; Child : Directory; begin Into.Tot_Size := 0; Into.Tot_Files := 0; Into.Tot_Dirs := 0; Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); begin if Kind = Ordinary_File then New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); begin New_File.Size := Ada.Directories.Size (Ent); exception when Constraint_Error => New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last); end; Into.Files.Append (New_File); if New_File.Size > 0 then begin Into.Tot_Size := Into.Tot_Size + New_File.Size; exception when Constraint_Error => Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size) & " for " & Path & "/" & Name); Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size)); end; end if; Into.Tot_Files := Into.Tot_Files + 1; elsif Name /= "." and Name /= ".." then if Into.Children = null then Into.Children := new Directory_Vector; end if; Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Into.Children.Append (Child); Into.Tot_Dirs := Into.Tot_Dirs + 1; end if; end; end loop; Scan_Children (Path, Into); Scan_Files (Path, Into); exception when E : others => Log.Error ("Exception ", E); end Scan; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- 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.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; overriding procedure Add_File (Into : in out File_Queue; Path : in String; Element : in File) is begin Into.Queue.Enqueue (Element); end Add_File; overriding procedure Add_Directory (Into : in out File_Queue; Path : in String; Name : in String) is begin Into.Directories.Append (Util.Files.Compose (Path, Name)); end Add_Directory; procedure Iterate_Files (Path : in String; Dir : in out Directory; Depth : in Natural; Update : access procedure (P : in String; F : in out File)) is use Ada.Strings.Unbounded; Iter : File_Vectors.Cursor := Dir.Files.First; procedure Iterate_File (Item : in out File) is begin Update (Path, Item); end Iterate_File; procedure Iterate_Child (Item : in out Directory) is begin Iterate_Files (Path & "/" & To_String (Item.Name), Item, Depth - 1, Update); end Iterate_Child; begin while File_Vectors.Has_Element (Iter) loop Dir.Files.Update_Element (Iter, Iterate_File'Access); File_Vectors.Next (Iter); end loop; if Depth > 0 and then Dir.Children /= null then declare Dir_Iter : Directory_Vectors.Cursor := Dir.Children.First; begin while Directory_Vectors.Has_Element (Dir_Iter) loop Dir.Children.Update_Element (Dir_Iter, Iterate_Child'Access); Directory_Vectors.Next (Dir_Iter); end loop; end; end if; end Iterate_Files; procedure Scan_Files (Path : in String; Into : in out Directory) is Iter : File_Vectors.Cursor := Into.Files.First; procedure Compute_Sha1 (Item : in out File) is begin Compute_Sha1 (Path, Item); end Compute_Sha1; begin while File_Vectors.Has_Element (Iter) loop Into.Files.Update_Element (Iter, Compute_Sha1'Access); File_Vectors.Next (Iter); end loop; end Scan_Files; procedure Scan_Children (Path : in String; Into : in out Directory) is procedure Update (Dir : in out Directory) is use Ada.Strings.Unbounded; use type Ada.Directories.File_Size; begin Scan (Path & "/" & To_String (Dir.Name), Dir); Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files; Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size; Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs; end Update; begin if Into.Children /= null then declare Iter : Directory_Vectors.Cursor := Into.Children.First; begin while Directory_Vectors.Has_Element (Iter) loop Into.Children.Update_Element (Iter, Update'Access); Directory_Vectors.Next (Iter); end loop; end; end if; end Scan_Children; procedure Scan (Path : in String; Into : in out Directory) is use Ada.Directories; Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; New_File : File; Child : Directory; begin Into.Tot_Size := 0; Into.Tot_Files := 0; Into.Tot_Dirs := 0; Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); begin if Kind = Ordinary_File then New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); begin New_File.Size := Ada.Directories.Size (Ent); exception when Constraint_Error => New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last); end; Into.Files.Append (New_File); if New_File.Size > 0 then begin Into.Tot_Size := Into.Tot_Size + New_File.Size; exception when Constraint_Error => Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size) & " for " & Path & "/" & Name); Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size)); end; end if; Into.Tot_Files := Into.Tot_Files + 1; elsif Name /= "." and Name /= ".." then if Into.Children = null then Into.Children := new Directory_Vector; end if; Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Into.Children.Append (Child); Into.Tot_Dirs := Into.Tot_Dirs + 1; end if; end; end loop; Scan_Children (Path, Into); Scan_Files (Path, Into); exception when E : others => Log.Error ("Exception ", E); end Scan; end Babel.Files;
Remove the old Compute_Sha1 procedure
Remove the old Compute_Sha1 procedure
Ada
apache-2.0
stcarrez/babel
0615c0d22719f638fe45aa9021260706ebd52075
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with Wiki.Strings; with AWA.Modules; with AWA.Blogs.Models; with AWA.Counters.Definition; with AWA.Blogs.Servlets; with Security.Permissions; -- == Integration == -- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application. -- It provides operations that are used by the blog beans or other services to create and update -- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- type Application is new AWA.Applications.Application with record -- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Blogs.Modules.NAME, -- URI => "blogs", -- Module => App.Blog_Module'Access); -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Define the read post counter. package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Get the image prefix that was configured for the Blog module. function Get_Image_Prefix (Module : in Blog_Module) return Wiki.Strings.UString; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private type Blog_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; Image_Servlet : aliased AWA.Blogs.Servlets.Image_Servlet; end record; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with ASF.Applications; with ADO; with Wiki.Strings; with AWA.Modules; with AWA.Blogs.Models; with AWA.Counters.Definition; with AWA.Blogs.Servlets; with Security.Permissions; -- == Integration == -- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application. -- It provides operations that are used by the blog beans or other services to create and update -- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the -- AWA application. The module instance can be defined as follows: -- -- type Application is new AWA.Applications.Application with record -- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Blogs.Modules.NAME, -- URI => "blogs", -- Module => App.Blog_Module'Access); -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); -- Define the read post counter. package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Blog_Module; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Get the image prefix that was configured for the Blog module. function Get_Image_Prefix (Module : in Blog_Module) return Wiki.Strings.UString; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Publish_Date : in ADO.Nullable_Time; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); -- Load the image data associated with a blog post. The image must be public and the -- post visible for the image to be retrieved by anonymous users. procedure Load_Image (Model : in Blog_Module; Post_Id : in ADO.Identifier; Image_Id : in ADO.Identifier; Width : in out Natural; Height : in out Natural; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); private type Blog_Module is new AWA.Modules.Module with record Image_Prefix : Wiki.Strings.UString; Image_Servlet : aliased AWA.Blogs.Servlets.Image_Servlet; end record; end AWA.Blogs.Modules;
Add a Publish_Date member to the Update_Post operation
Add a Publish_Date member to the Update_Post operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1d355e2271d0dac8129b827a38eed114dc88b6d8
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; package AWA.Workspaces.Modules is Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; package AWA.Workspaces.Modules is Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; end record; end AWA.Workspaces.Modules;
Declare the Accept_Invitation procedure
Declare the Accept_Invitation procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
60914fde3ada137d983bf2a95688c0ea8bc9e595
awa/plugins/awa-questions/src/awa-questions.ads
awa/plugins/awa-questions/src/awa-questions.ads
----------------------------------------------------------------------- -- awa-questions -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package AWA.Questions is end AWA.Questions;
----------------------------------------------------------------------- -- awa-questions -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package AWA.Questions is pragma Preelaborate; end AWA.Questions;
Add Preelaborate
Add Preelaborate
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
db0d428c98cc1491a8c8a142fbfc9d8fa07a50e7
awa/plugins/awa-images/src/awa-images-services.ads
awa/plugins/awa-images/src/awa-images-services.ads
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with AWA.Modules; with EL.Expressions; with AWA.Storages.Models; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package AWA.Images.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); PARAM_THUMBNAIL_COMMAND : constant String := "thumbnail_command"; -- ------------------------------ -- Image Service -- ------------------------------ -- The <b>Image_Service</b> works closely with the storage service. It extracts the -- information of an image, creates the image thumbnail. type Image_Service is new AWA.Modules.Module_Manager with private; type Image_Service_Access is access all Image_Service'Class; -- Initializes the image service. overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class); procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); private type Image_Service is new AWA.Modules.Module_Manager with record Thumbnail_Command : EL.Expressions.Expression; end record; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with ADO; with AWA.Modules; with EL.Expressions; with AWA.Storages.Models; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package AWA.Images.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); PARAM_THUMBNAIL_COMMAND : constant String := "thumbnail_command"; -- ------------------------------ -- Image Service -- ------------------------------ -- The <b>Image_Service</b> works closely with the storage service. It extracts the -- information of an image, creates the image thumbnail. type Image_Service is new AWA.Modules.Module_Manager with private; type Image_Service_Access is access all Image_Service'Class; -- Initializes the image service. overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class); procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural); -- Build a thumbnail for the image identified by the Id. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class); private type Image_Service is new AWA.Modules.Module_Manager with record Thumbnail_Command : EL.Expressions.Expression; end record; end AWA.Images.Services;
Declare the Build_Thumbnail procedure
Declare the Build_Thumbnail procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4106d8d4e935bcd56acb3731e7a65e38b983ee9a
src/os-win32/util-processes-os.ads
src/os-win32/util-processes-os.ads
----------------------------------------------------------------------- -- util-processes-os -- Windows specific and low level operations -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Raw; with Util.Systems.Os; with Interfaces.C; private package Util.Processes.Os is use Util.Systems.Os; type Wchar_Ptr is access all Interfaces.C.wchar_array; type System_Process is new Util.Processes.System_Process with record Process_Info : aliased Util.Systems.Os.PROCESS_INFORMATION; Command : Wchar_Ptr := null; Pos : Interfaces.C.size_t := 0; end record; -- Wait for the process to exit. overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration); -- Spawn a new process. overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15); -- Append the argument to the process argument list. overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String); -- Set the process input, output and error streams to redirect and use specified files. overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean); -- Deletes the storage held by the system process. overriding procedure Finalize (Sys : in out System_Process); -- Build the output pipe redirection to read the process output. procedure Build_Output_Pipe (Proc : in out Process'Class; Into : in out Startup_Info); -- Build the input pipe redirection to write the process standard input. procedure Build_Input_Pipe (Proc : in out Process'Class; Into : in out Startup_Info); private -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. function Create_Stream (File : in Util.Streams.Raw.File_Type) return Util.Streams.Raw.Raw_Stream_Access; end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- Windows specific and low level operations -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Raw; with Util.Systems.Os; with Interfaces.C; private package Util.Processes.Os is use Util.Systems.Os; SHELL : constant String := ""; type Wchar_Ptr is access all Interfaces.C.wchar_array; type System_Process is new Util.Processes.System_Process with record Process_Info : aliased Util.Systems.Os.PROCESS_INFORMATION; Command : Wchar_Ptr := null; Pos : Interfaces.C.size_t := 0; end record; -- Wait for the process to exit. overriding procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration); -- Spawn a new process. overriding procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. overriding procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15); -- Append the argument to the process argument list. overriding procedure Append_Argument (Sys : in out System_Process; Arg : in String); -- Set the process input, output and error streams to redirect and use specified files. overriding procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean); -- Deletes the storage held by the system process. overriding procedure Finalize (Sys : in out System_Process); -- Build the output pipe redirection to read the process output. procedure Build_Output_Pipe (Proc : in out Process'Class; Into : in out Startup_Info); -- Build the input pipe redirection to write the process standard input. procedure Build_Input_Pipe (Proc : in out Process'Class; Into : in out Startup_Info); private -- Create the output stream to read/write on the process input/output. -- Setup the file to be closed on exec. function Create_Stream (File : in Util.Streams.Raw.File_Type) return Util.Streams.Raw.Raw_Stream_Access; end Util.Processes.Os;
Declare the SHELL constant (empty so that we use the default argument splitting method)
Declare the SHELL constant (empty so that we use the default argument splitting method)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util