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
0c1a5cc98c6224b96a422998909afc636c209133
src/babel-strategies.ads
src/babel-strategies.ads
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files; with Babel.Files.Buffers; with Babel.Stores; with Babel.Filters; package Babel.Strategies is type Strategy_Type is abstract limited new Babel.Files.File_Container with private; type Strategy_Type_Access is access all Strategy_Type'Class; -- Allocate a buffer to read the file content. function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access; -- Release the buffer that was allocated by Allocate_Buffer. procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access); -- Returns true if there is a directory that must be processed by the current strategy. function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract; -- Get the next directory that must be processed by the strategy. function Peek_Directory (Strategy : in out Strategy_Type) return String is abstract; procedure Scan (Strategy : in out Strategy_Type; Path : in String); -- Read the file from the read store into the local buffer. procedure Read_File (Strategy : in Strategy_Type; File : in Babel.Files.File; Into : in Babel.Files.Buffers.Buffer_Access); -- Write the file from the local buffer into the write store. procedure Write_File (Strategy : in Strategy_Type; File : in Babel.Files.File; Content : in Babel.Files.Buffers.Buffer_Access); -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in Strategy_Type; File : in Babel.Files.File; Content : in out Babel.Files.Buffers.Buffer_Access); procedure Execute (Strategy : in out Strategy_Type) is abstract; -- Set the file filters that will be used when scanning the read store. procedure Set_Filters (Strategy : in out Strategy_Type; Filters : in Babel.Filters.Filter_Type_Access); -- Set the read and write stores that the strategy will use. procedure Set_Stores (Strategy : in out Strategy_Type; Read : in Babel.Stores.Store_Type_Access; Write : in Babel.Stores.Store_Type_Access); -- Set the buffer pool to be used by Allocate_Buffer. procedure Set_Buffers (Strategy : in out Strategy_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access); private type Strategy_Type is abstract limited new Babel.Files.File_Container with record Read_Store : Babel.Stores.Store_Type_Access; Write_Store : Babel.Stores.Store_Type_Access; Filters : Babel.Filters.Filter_Type_Access; Buffers : Babel.Files.Buffers.Buffer_Pool_Access; end record; 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. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files; with Babel.Files.Buffers; with Babel.Stores; with Babel.Filters; package Babel.Strategies is type Strategy_Type is abstract limited new Babel.Files.File_Container with private; type Strategy_Type_Access is access all Strategy_Type'Class; -- Allocate a buffer to read the file content. function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access; -- Release the buffer that was allocated by Allocate_Buffer. procedure Release_Buffer (Strategy : in Strategy_Type; Buffer : in out Babel.Files.Buffers.Buffer_Access); -- Returns true if there is a directory that must be processed by the current strategy. function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract; -- Get the next directory that must be processed by the strategy. function Peek_Directory (Strategy : in out Strategy_Type) return String is abstract; procedure Scan (Strategy : in out Strategy_Type; Path : in String); -- Read the file from the read store into the local buffer. procedure Read_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Into : in Babel.Files.Buffers.Buffer_Access); -- Write the file from the local buffer into the write store. procedure Write_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in Babel.Files.Buffers.Buffer_Access); -- Backup the file from the local buffer into the write store. procedure Backup_File (Strategy : in Strategy_Type; File : in Babel.Files.File_Type; Content : in out Babel.Files.Buffers.Buffer_Access); procedure Execute (Strategy : in out Strategy_Type) is abstract; -- Set the file filters that will be used when scanning the read store. procedure Set_Filters (Strategy : in out Strategy_Type; Filters : in Babel.Filters.Filter_Type_Access); -- Set the read and write stores that the strategy will use. procedure Set_Stores (Strategy : in out Strategy_Type; Read : in Babel.Stores.Store_Type_Access; Write : in Babel.Stores.Store_Type_Access); -- Set the buffer pool to be used by Allocate_Buffer. procedure Set_Buffers (Strategy : in out Strategy_Type; Buffers : in Babel.Files.Buffers.Buffer_Pool_Access); private type Strategy_Type is abstract limited new Babel.Files.File_Container with record Read_Store : Babel.Stores.Store_Type_Access; Write_Store : Babel.Stores.Store_Type_Access; Filters : Babel.Filters.Filter_Type_Access; Buffers : Babel.Files.Buffers.Buffer_Pool_Access; end record; end Babel.Strategies;
Change to use the File_Type type
Change to use the File_Type type
Ada
apache-2.0
stcarrez/babel
f6ddfbb61f31eb338fabd2b9160429ff7afee274
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 (IRQn_As_Word and 16#1F#, 1); 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 Enable_Interrupt
Cortex_M.NVIC: Fix Enable_Interrupt The arguments of the left shits are reversed.
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
a1741f8eddfbf3ffddf4dcab0735ae886aa660bf
awa/plugins/awa-storages/src/awa-storages-stores.ads
awa/plugins/awa-storages/src/awa-storages-stores.ads
----------------------------------------------------------------------- -- awa-storages-stores -- The storage interface -- 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 ADO.Sessions; with AWA.Storages.Models; -- == Store Service == -- The `AWA.Storages.Stores` package defines the interface that a store must implement to -- be able to save and retrieve a data content. package AWA.Storages.Stores is -- ------------------------------ -- Store Service -- ------------------------------ type Store is limited interface; type Store_Access is access all Store'Class; -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. procedure Save (Storage : in Store; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is abstract; procedure Load (Storage : in Store; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in String) is abstract; end AWA.Storages.Stores;
----------------------------------------------------------------------- -- awa-storages-stores -- The storage interface -- 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 ADO.Sessions; with AWA.Storages.Models; -- == Store Service == -- The `AWA.Storages.Stores` package defines the interface that a store must implement to -- be able to save and retrieve a data content. package AWA.Storages.Stores is -- ------------------------------ -- Store Service -- ------------------------------ type Store is limited interface; type Store_Access is access all Store'Class; -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. procedure Save (Storage : in Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is abstract; procedure Load (Storage : in Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in String) is abstract; end AWA.Storages.Stores;
Add the database session as parameter to the store implementation
Add the database session as parameter to the store implementation
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
941583daea3f2e1b97c8f78c6aebcaadb41d79a7
src/orka/implementation/glfw/orka-inputs-glfw.adb
src/orka/implementation/glfw/orka-inputs-glfw.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Strings.Unbounded; with Glfw.Input.Joysticks; with Orka.Inputs.Joysticks.Default; with Orka.Inputs.Joysticks.Gamepads; package body Orka.Inputs.GLFW is overriding procedure Set_Cursor_Mode (Object : in out GLFW_Pointer_Input; Mode : Pointers.Default.Cursor_Mode) is package Mouse renames Standard.Glfw.Input.Mouse; use all type Pointers.Default.Cursor_Mode; begin case Mode is when Normal => Object.Window.Set_Cursor_Mode (Mouse.Normal); when Hidden => Object.Window.Set_Cursor_Mode (Mouse.Hidden); when Disabled => Object.Window.Set_Cursor_Mode (Mouse.Disabled); end case; end Set_Cursor_Mode; procedure Set_Button_State (Object : in out GLFW_Pointer_Input; Subject : Standard.Glfw.Input.Mouse.Button; State : Standard.Glfw.Input.Button_State) is use Standard.Glfw.Input; use all type Inputs.Pointers.Button; use all type Inputs.Pointers.Button_State; Pointer_State : constant Pointers.Button_State := (case State is when Pressed => Pressed, when Released => Released); begin case Subject is when Mouse.Left_Button => Object.Set_Button_State (Left, Pointer_State); when Mouse.Right_Button => Object.Set_Button_State (Right, Pointer_State); when Mouse.Middle_Button => Object.Set_Button_State (Middle, Pointer_State); when others => raise Program_Error with "Invalid mouse button"; end case; end Set_Button_State; procedure Set_Window (Object : in out GLFW_Pointer_Input; Window : Standard.Glfw.Windows.Window_Reference) is begin Object.Window := Window; end Set_Window; function Create_Pointer_Input return Inputs.Pointers.Pointer_Input_Ptr is begin return new GLFW_Pointer_Input' (Pointers.Default.Abstract_Pointer_Input with others => <>); end Create_Pointer_Input; ----------------------------------------------------------------------------- use Inputs.Joysticks; procedure Copy_Buttons (From : Standard.Glfw.Input.Joysticks.Joystick_Button_States; To : out Inputs.Joysticks.Button_States) is use all type Standard.Glfw.Input.Joysticks.Joystick_Button_State; begin for Index in From'Range loop To (Index) := (case From (Index) is when Pressed => Pressed, when Released => Released); end loop; end Copy_Buttons; procedure Copy_Axes (From : Standard.Glfw.Input.Joysticks.Axis_Positions; To : out Inputs.Joysticks.Axis_Positions) is begin for Index in From'Range loop To (Index) := Axis_Position (From (Index)); end loop; end Copy_Axes; procedure Copy_Hats (From : Standard.Glfw.Input.Joysticks.Joystick_Hat_States; To : out Inputs.Joysticks.Hat_States) is use all type Standard.Glfw.Input.Joysticks.Joystick_Hat_State; begin for Index in From'Range loop To (Index) := (case From (Index) is when Centered => Centered, when Up => Up, when Right => Right, when Right_Up => Right_Up, when Down => Down, when Right_Down => Right_Down, when Left => Left, when Left_Up => Left_Up, when Left_Down => Left_Down); end loop; end Copy_Hats; ----------------------------------------------------------------------------- package SU renames Ada.Strings.Unbounded; type Abstract_GLFW_Joystick_Input is abstract new Joysticks.Default.Abstract_Joystick_Input with record Joystick : Standard.Glfw.Input.Joysticks.Joystick; Name, GUID : SU.Unbounded_String; Present : Boolean; end record; overriding function Is_Present (Object : Abstract_GLFW_Joystick_Input) return Boolean is (Object.Present and then Object.Joystick.Is_Present); overriding function Name (Object : Abstract_GLFW_Joystick_Input) return String is (SU.To_String (Object.Name)); overriding function GUID (Object : Abstract_GLFW_Joystick_Input) return String is (SU.To_String (Object.GUID)); ----------------------------------------------------------------------------- type GLFW_Gamepad_Input is new Abstract_GLFW_Joystick_Input with null record; overriding function Is_Gamepad (Object : GLFW_Gamepad_Input) return Boolean is (True); overriding function State (Object : in out GLFW_Gamepad_Input) return Inputs.Joysticks.Joystick_State is use type SU.Unbounded_String; begin if not Object.Joystick.Is_Present then Object.Present := False; raise Disconnected_Error with Object.Joystick.Index'Image & " is not connected"; elsif Object.Joystick.Joystick_GUID = Object.GUID then Object.Present := True; end if; declare State : constant Standard.Glfw.Input.Joysticks.Joystick_Gamepad_State := Object.Joystick.Gamepad_State; begin return Result : Joystick_State (Button_Count => State.Buttons'Length, Axis_Count => State.Axes'Length, Hat_Count => 0) do Copy_Buttons (State.Buttons, Result.Buttons); Copy_Axes (State.Axes, Result.Axes); Inputs.Joysticks.Gamepads.Normalize_Axes (Result.Axes); end return; end; end State; ----------------------------------------------------------------------------- type GLFW_Joystick_Input is new Abstract_GLFW_Joystick_Input with null record; overriding function Is_Gamepad (Object : GLFW_Joystick_Input) return Boolean is (False); overriding function State (Object : in out GLFW_Joystick_Input) return Inputs.Joysticks.Joystick_State is use type SU.Unbounded_String; begin if not Object.Joystick.Is_Present then Object.Present := False; raise Disconnected_Error with Object.Joystick.Index'Image & " is not connected"; elsif Object.Joystick.Joystick_GUID = Object.GUID then Object.Present := True; end if; declare Buttons : constant Standard.Glfw.Input.Joysticks.Joystick_Button_States := Object.Joystick.Button_States; Axes : constant Standard.Glfw.Input.Joysticks.Axis_Positions := Object.Joystick.Positions; Hats : constant Standard.Glfw.Input.Joysticks.Joystick_Hat_States := Object.Joystick.Hat_States; begin return Result : Joystick_State (Button_Count => Buttons'Length, Axis_Count => Axes'Length, Hat_Count => Hats'Length) do Copy_Buttons (Buttons, Result.Buttons); Copy_Axes (Axes, Result.Axes); Copy_Hats (Hats, Result.Hats); end return; end; end State; ----------------------------------------------------------------------------- function Create_Joystick_Input (Index : Standard.Glfw.Input.Joysticks.Joystick_Index) return Inputs.Joysticks.Joystick_Input_Ptr is Joystick : constant Standard.Glfw.Input.Joysticks.Joystick := Standard.Glfw.Input.Joysticks.Get_Joystick (Index); begin if not Joystick.Is_Present then raise Disconnected_Error with Index'Image & " is not connected"; end if; if Joystick.Is_Gamepad then return new GLFW_Gamepad_Input' (Joysticks.Default.Abstract_Joystick_Input with Joystick => Joystick, Present => True, Name => SU.To_Unbounded_String (Joystick.Gamepad_Name), GUID => SU.To_Unbounded_String (Joystick.Joystick_GUID)); else return new GLFW_Joystick_Input' (Joysticks.Default.Abstract_Joystick_Input with Joystick => Joystick, Present => True, Name => SU.To_Unbounded_String (Joystick.Gamepad_Name), GUID => SU.To_Unbounded_String (Joystick.Joystick_GUID)); end if; end Create_Joystick_Input; ----------------------------------------------------------------------------- subtype Slot_Index is Standard.Glfw.Input.Joysticks.Joystick_Index range 1 .. 16; type Boolean_Array is array (Slot_Index) of Boolean; protected type Joystick_Manager is new Inputs.Joysticks.Joystick_Manager with procedure Set_Present (Index : Slot_Index; Value : Boolean); procedure Initialize with Post => Is_Initialized; function Is_Initialized return Boolean; overriding procedure Acquire (Joystick : out Inputs.Joysticks.Joystick_Input_Access); overriding procedure Release (Joystick : Inputs.Joysticks.Joystick_Input_Access); private Acquired, Present : Boolean_Array := (others => False); Initialized : Boolean := False; end Joystick_Manager; package Joysticks renames Standard.Glfw.Input.Joysticks; protected body Joystick_Manager is procedure Set_Present (Index : Slot_Index; Value : Boolean) is begin Present (Index) := Value; end Set_Present; procedure Initialize is begin for Index in Present'Range loop Present (Index) := Joysticks.Get_Joystick (Index).Is_Present; end loop; Initialized := True; end Initialize; function Is_Initialized return Boolean is (Initialized); procedure Acquire (Joystick : out Inputs.Joysticks.Joystick_Input_Access) is begin for Index in Acquired'Range loop if not Acquired (Index) and Present (Index) then Joystick := Create_Joystick_Input (Index); Acquired (Index) := True; return; end if; end loop; Joystick := null; end Acquire; procedure Release (Joystick : Inputs.Joysticks.Joystick_Input_Access) is Index : constant Slot_Index := Abstract_GLFW_Joystick_Input (Joystick.all).Joystick.Index; begin if not Acquired (Index) then raise Program_Error; end if; Acquired (Index) := False; end Release; end Joystick_Manager; Default_Manager : aliased Joystick_Manager; procedure On_Connected (Source : Joysticks.Joystick; State : Joysticks.Connect_State) is use type Joysticks.Connect_State; begin Default_Manager.Set_Present (Source.Index, State = Joysticks.Connected); end On_Connected; function Create_Joystick_Manager return Inputs.Joysticks.Joystick_Manager_Ptr is begin if not Default_Manager.Is_Initialized then Default_Manager.Initialize; Joysticks.Set_Callback (On_Connected'Access); end if; return Default_Manager'Access; end Create_Joystick_Manager; end Orka.Inputs.GLFW;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Strings.Unbounded; with Glfw.Input.Joysticks; with Orka.Inputs.Joysticks.Default; with Orka.Inputs.Joysticks.Gamepads; package body Orka.Inputs.GLFW is overriding procedure Set_Cursor_Mode (Object : in out GLFW_Pointer_Input; Mode : Pointers.Default.Cursor_Mode) is package Mouse renames Standard.Glfw.Input.Mouse; use all type Pointers.Default.Cursor_Mode; begin case Mode is when Normal => Object.Window.Set_Cursor_Mode (Mouse.Normal); when Hidden => Object.Window.Set_Cursor_Mode (Mouse.Hidden); when Disabled => Object.Window.Set_Cursor_Mode (Mouse.Disabled); end case; end Set_Cursor_Mode; procedure Set_Button_State (Object : in out GLFW_Pointer_Input; Subject : Standard.Glfw.Input.Mouse.Button; State : Standard.Glfw.Input.Button_State) is use Standard.Glfw.Input; use all type Inputs.Pointers.Button; use all type Inputs.Pointers.Button_State; Pointer_State : constant Pointers.Button_State := (case State is when Pressed => Pressed, when Released => Released); begin case Subject is when Mouse.Left_Button => Object.Set_Button_State (Left, Pointer_State); when Mouse.Right_Button => Object.Set_Button_State (Right, Pointer_State); when Mouse.Middle_Button => Object.Set_Button_State (Middle, Pointer_State); when others => raise Program_Error with "Invalid mouse button"; end case; end Set_Button_State; procedure Set_Window (Object : in out GLFW_Pointer_Input; Window : Standard.Glfw.Windows.Window_Reference) is begin Object.Window := Window; end Set_Window; function Create_Pointer_Input return Inputs.Pointers.Pointer_Input_Ptr is begin return new GLFW_Pointer_Input' (Pointers.Default.Abstract_Pointer_Input with others => <>); end Create_Pointer_Input; ----------------------------------------------------------------------------- use Inputs.Joysticks; procedure Copy_Buttons (From : Standard.Glfw.Input.Joysticks.Joystick_Button_States; To : out Inputs.Joysticks.Button_States) is use all type Standard.Glfw.Input.Joysticks.Joystick_Button_State; begin for Index in From'Range loop To (Index) := (case From (Index) is when Pressed => Pressed, when Released => Released); end loop; end Copy_Buttons; procedure Copy_Axes (From : Standard.Glfw.Input.Joysticks.Axis_Positions; To : out Inputs.Joysticks.Axis_Positions) is begin for Index in From'Range loop To (Index) := Axis_Position (From (Index)); end loop; end Copy_Axes; procedure Copy_Hats (From : Standard.Glfw.Input.Joysticks.Joystick_Hat_States; To : out Inputs.Joysticks.Hat_States) is use all type Standard.Glfw.Input.Joysticks.Joystick_Hat_State; begin for Index in From'Range loop To (Index) := (case From (Index) is when Centered => Centered, when Up => Up, when Right => Right, when Right_Up => Right_Up, when Down => Down, when Right_Down => Right_Down, when Left => Left, when Left_Up => Left_Up, when Left_Down => Left_Down); end loop; end Copy_Hats; ----------------------------------------------------------------------------- package SU renames Ada.Strings.Unbounded; type Abstract_GLFW_Joystick_Input is abstract new Joysticks.Default.Abstract_Joystick_Input with record Joystick : Standard.Glfw.Input.Joysticks.Joystick; Name, GUID : SU.Unbounded_String; Present : Boolean; end record; overriding function Is_Present (Object : Abstract_GLFW_Joystick_Input) return Boolean is (Object.Present and then Object.Joystick.Is_Present); overriding function Name (Object : Abstract_GLFW_Joystick_Input) return String is (SU.To_String (Object.Name)); overriding function GUID (Object : Abstract_GLFW_Joystick_Input) return String is (SU.To_String (Object.GUID)); ----------------------------------------------------------------------------- type GLFW_Gamepad_Input is new Abstract_GLFW_Joystick_Input with null record; overriding function Is_Gamepad (Object : GLFW_Gamepad_Input) return Boolean is (True); overriding function State (Object : in out GLFW_Gamepad_Input) return Inputs.Joysticks.Joystick_State is use type SU.Unbounded_String; begin if not Object.Joystick.Is_Present then Object.Present := False; raise Disconnected_Error with Object.Joystick.Index'Image & " is not connected"; elsif Object.Joystick.Joystick_GUID = Object.GUID then Object.Present := True; end if; declare State : constant Standard.Glfw.Input.Joysticks.Joystick_Gamepad_State := Object.Joystick.Gamepad_State; begin return Result : Joystick_State (Button_Count => State.Buttons'Length, Axis_Count => State.Axes'Length, Hat_Count => 0) do Copy_Buttons (State.Buttons, Result.Buttons); Copy_Axes (State.Axes, Result.Axes); Inputs.Joysticks.Gamepads.Normalize_Axes (Result.Axes); end return; end; end State; ----------------------------------------------------------------------------- type GLFW_Joystick_Input is new Abstract_GLFW_Joystick_Input with null record; overriding function Is_Gamepad (Object : GLFW_Joystick_Input) return Boolean is (False); overriding function State (Object : in out GLFW_Joystick_Input) return Inputs.Joysticks.Joystick_State is use type SU.Unbounded_String; begin if not Object.Joystick.Is_Present then Object.Present := False; raise Disconnected_Error with Object.Joystick.Index'Image & " is not connected"; elsif Object.Joystick.Joystick_GUID = Object.GUID then Object.Present := True; end if; declare Buttons : constant Standard.Glfw.Input.Joysticks.Joystick_Button_States := Object.Joystick.Button_States; Axes : constant Standard.Glfw.Input.Joysticks.Axis_Positions := Object.Joystick.Positions; Hats : constant Standard.Glfw.Input.Joysticks.Joystick_Hat_States := Object.Joystick.Hat_States; begin return Result : Joystick_State (Button_Count => Buttons'Length, Axis_Count => Axes'Length, Hat_Count => Hats'Length) do Copy_Buttons (Buttons, Result.Buttons); Copy_Axes (Axes, Result.Axes); Copy_Hats (Hats, Result.Hats); end return; end; end State; ----------------------------------------------------------------------------- function Create_Joystick_Input (Index : Standard.Glfw.Input.Joysticks.Joystick_Index) return Inputs.Joysticks.Joystick_Input_Ptr is Joystick : constant Standard.Glfw.Input.Joysticks.Joystick := Standard.Glfw.Input.Joysticks.Get_Joystick (Index); begin if not Joystick.Is_Present then raise Disconnected_Error with Index'Image & " is not connected"; end if; if Joystick.Is_Gamepad then return new GLFW_Gamepad_Input' (Joysticks.Default.Abstract_Joystick_Input with Joystick => Joystick, Present => True, Name => SU.To_Unbounded_String (Joystick.Gamepad_Name), GUID => SU.To_Unbounded_String (Joystick.Joystick_GUID)); else return new GLFW_Joystick_Input' (Joysticks.Default.Abstract_Joystick_Input with Joystick => Joystick, Present => True, Name => SU.To_Unbounded_String (Joystick.Joystick_Name), GUID => SU.To_Unbounded_String (Joystick.Joystick_GUID)); end if; end Create_Joystick_Input; ----------------------------------------------------------------------------- subtype Slot_Index is Standard.Glfw.Input.Joysticks.Joystick_Index range 1 .. 16; type Boolean_Array is array (Slot_Index) of Boolean; protected type Joystick_Manager is new Inputs.Joysticks.Joystick_Manager with procedure Set_Present (Index : Slot_Index; Value : Boolean); procedure Initialize with Post => Is_Initialized; function Is_Initialized return Boolean; overriding procedure Acquire (Joystick : out Inputs.Joysticks.Joystick_Input_Access); overriding procedure Release (Joystick : Inputs.Joysticks.Joystick_Input_Access); private Acquired, Present : Boolean_Array := (others => False); Initialized : Boolean := False; end Joystick_Manager; package Joysticks renames Standard.Glfw.Input.Joysticks; protected body Joystick_Manager is procedure Set_Present (Index : Slot_Index; Value : Boolean) is begin Present (Index) := Value; end Set_Present; procedure Initialize is begin for Index in Present'Range loop Present (Index) := Joysticks.Get_Joystick (Index).Is_Present; end loop; Initialized := True; end Initialize; function Is_Initialized return Boolean is (Initialized); procedure Acquire (Joystick : out Inputs.Joysticks.Joystick_Input_Access) is begin for Index in Acquired'Range loop if not Acquired (Index) and Present (Index) then Joystick := Create_Joystick_Input (Index); Acquired (Index) := True; return; end if; end loop; Joystick := null; end Acquire; procedure Release (Joystick : Inputs.Joysticks.Joystick_Input_Access) is Index : constant Slot_Index := Abstract_GLFW_Joystick_Input (Joystick.all).Joystick.Index; begin if not Acquired (Index) then raise Program_Error; end if; Acquired (Index) := False; end Release; end Joystick_Manager; Default_Manager : aliased Joystick_Manager; procedure On_Connected (Source : Joysticks.Joystick; State : Joysticks.Connect_State) is use type Joysticks.Connect_State; begin Default_Manager.Set_Present (Source.Index, State = Joysticks.Connected); end On_Connected; function Create_Joystick_Manager return Inputs.Joysticks.Joystick_Manager_Ptr is begin if not Default_Manager.Is_Initialized then Default_Manager.Initialize; Joysticks.Set_Callback (On_Connected'Access); end if; return Default_Manager'Access; end Create_Joystick_Manager; end Orka.Inputs.GLFW;
Call Joystick_Name if not a gamepad to avoid null dereference
orka: Call Joystick_Name if not a gamepad to avoid null dereference Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
1ea7d809c9ccf8da8a56c1951bca50db3bf00424
seven-words/ada/src/Trie.adb
seven-words/ada/src/Trie.adb
with Ada.Text_IO; package body Trie is package IO renames Ada.Text_IO; procedure Add_Word(node : in out Trie_Node; word, partial : String; node_count : in out Natural) is first : Character; begin if partial'Length = 0 then node.is_terminal := true; node.word := BoundedString.To_Bounded_String(word); else first := partial(partial'First); if node.children(first) = null then node_count := node_count + 1; node.children(first) := new Trie_Node; end if; Add_Word(node.children(first).all, word, partial(partial'First + 1 .. partial'Last), node_count); end if; end Add_Word; function Find_Partial(node : in Trie_Node_Access; word : String) return Trie_Node_Access is begin if node = null or else word'Length = 0 then return node; else return Find_Partial(node.all.children(word(word'First)), word(word'First + 1 .. word'Last)); end if; end Find_Partial; function Make_Trie(filename : String) return Trie is input : IO.File_Type; result : Trie; word : String (1 .. 32); last : Natural; begin IO.Open(input, IO.In_File, filename); result.node_count := 0; result.root := new Trie_Node; while not IO.End_Of_File(input) loop IO.Get_Line(input, word, last); if last = word'Last then raise Constraint_Error; elsif last > 3 and last < BoundedString.Max_Length then Add_Word(result.root.all, word(1 .. last), word(1 .. last), result.node_count); end if; end loop; return result; end Make_Trie; procedure Find_Words(words : Trie; fragments: String; endpoints: Fragment_Endpoint_Array) is taken : Array (fragments'Range) of Boolean := (others => False); procedure Find_Words_Helper(node : Trie_Node_Access ) is new_node : Trie_Node_Access; begin for index in endpoints'Range loop if not taken(index) then new_node := Find_Partial(node, fragments(endpoints(index).first .. endpoints(index).last)); if new_node /= null then taken(index) := True; if new_node.all.is_terminal then IO.Put_Line(BoundedString.To_String(new_node.all.word)); end if; Find_Words_Helper(new_node); taken(index) := False; end if; end if; end loop; end Find_Words_Helper; begin IO.Put_Line(fragments); Find_Words_Helper(words.root); end Find_Words; end Trie;
with Ada.Text_IO; package body Trie is package IO renames Ada.Text_IO; procedure Add_Word(node : in out Trie_Node; word, partial : String; node_count : in out Natural) is first : Character; begin if partial'Length = 0 then node.is_terminal := true; node.word := BoundedString.To_Bounded_String(word); else first := partial(partial'First); if node.children(first) = null then node_count := node_count + 1; node.children(first) := new Trie_Node; end if; Add_Word(node.children(first).all, word, partial(partial'First + 1 .. partial'Last), node_count); end if; end Add_Word; function Find_Partial(node : in Trie_Node_Access; word : String) return Trie_Node_Access is begin if node = null or else word'Length = 0 then return node; else return Find_Partial(node.all.children(word(word'First)), word(word'First + 1 .. word'Last)); end if; end Find_Partial; function Make_Trie(filename : String) return Trie is input : IO.File_Type; result : Trie; word : String (1 .. 32); last : Natural; begin IO.Open(input, IO.In_File, filename); result.node_count := 0; result.root := new Trie_Node; while not IO.End_Of_File(input) loop IO.Get_Line(input, word, last); if last = word'Last then raise Constraint_Error; elsif last > 3 and last < BoundedString.Max_Length then Add_Word(result.root.all, word(1 .. last), word(1 .. last), result.node_count); end if; end loop; return result; end Make_Trie; procedure Find_Words(words : Trie; fragments: String; endpoints: Fragment_Endpoint_Array) is taken : Array (fragments'Range) of Boolean := (others => False); procedure Find_Words_Helper(node : Trie_Node_Access ) is new_node : Trie_Node_Access; begin for index in endpoints'Range loop if not taken(index) then new_node := Find_Partial(node, fragments(endpoints(index).first .. endpoints(index).last)); if new_node /= null then taken(index) := True; if new_node.all.is_terminal then IO.Put_Line(BoundedString.To_String(new_node.all.word)); end if; Find_Words_Helper(new_node); taken(index) := False; end if; end if; end loop; end Find_Words_Helper; begin IO.Put_Line(fragments); Find_Words_Helper(words.root); end Find_Words; end Trie;
Fix indentation.
Fix indentation.
Ada
unlicense
Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch
9ff2b654ef356ea66e3a12f3caab5da9c64607fa
src/ado-sessions-factory.adb
src/ado-sessions-factory.adb
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; with ADO.Schemas.Entities; with ADO.Queries.Loaders; package body ADO.Sessions.Factory is -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; with ADO.Schemas.Entities; with ADO.Queries.Loaders; package body ADO.Sessions.Factory is -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unchecked_Access; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; S.Queries := Factory.Queries'Unrestricted_Access; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; end ADO.Sessions.Factory;
Replace the Query_Manager_Access by a Query_Manager
Replace the Query_Manager_Access by a Query_Manager
Ada
apache-2.0
stcarrez/ada-ado
7072978a6cfbc43b65a91b30b4791d559bc5f6cd
src/asf-components-utils.adb
src/asf-components-utils.adb
----------------------------------------------------------------------- -- components-util -- ASF Util Components -- 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 ASF.Views; with ASF.Views.Nodes; package body ASF.Components.Utils is function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info; -- ------------------------------ -- Get the line information where the component is defined. -- ------------------------------ function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info is Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag; begin if Tag /= null then return Tag.Get_Line_Info; else return Tag.Get_Line_Info; end if; end Get_Line_Info; pragma Unreferenced (Get_Line_Info); -- ------------------------------ -- Get the line information where the component is defined. -- ------------------------------ function Get_Line_Info (UI : in Base.UIComponent'Class) return String is Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag; begin if Tag /= null then return Tag.Get_Line_Info; else return Tag.Get_Line_Info; end if; end Get_Line_Info; end ASF.Components.Utils;
----------------------------------------------------------------------- -- components-util -- ASF Util Components -- 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 ASF.Views; with ASF.Views.Nodes; package body ASF.Components.Utils is function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info; -- ------------------------------ -- Get the line information where the component is defined. -- ------------------------------ function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info is Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag; begin if Tag /= null then return Tag.Get_Line_Info; else return Tag.Get_Line_Info; end if; end Get_Line_Info; pragma Unreferenced (Get_Line_Info); -- ------------------------------ -- Get the line information where the component is defined. -- ------------------------------ function Get_Line_Info (UI : in Base.UIComponent'Class) return String is Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag; begin if Tag /= null then return Tag.Get_Line_Info; else return "?"; end if; end Get_Line_Info; end ASF.Components.Utils;
Fix exception in case the component has no associated tag
Fix exception in case the component has no associated tag
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f7e8d4a21d3d43ea2ea852686ce034a2d5f6557c
src/gen-commands-plugins.adb
src/gen-commands-plugins.adb
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with Gen.Model.Projects; with GNAT.Command_Line; with Util.Files; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Plugins is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Result_Dir : constant String := Generator.Get_Result_Directory; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l:") is when ASCII.NUL => exit; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; declare Name : constant String := Get_Argument; Kind : constant String := Get_Argument; Dir : constant String := Generator.Get_Plugin_Directory; Path : constant String := Util.Files.Compose (Dir, Name); begin if Name'Length = 0 then Generator.Error ("Missing plugin name"); Gen.Commands.Usage; return; end if; if Kind /= "ada" and Kind /= "web" and Kind /= "" then Generator.Error ("Invalid plugin type (must be 'ada' or 'web')"); return; end if; if Ada.Directories.Exists (Path) then Generator.Error ("Plugin {0} exists already", Name); return; end if; if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Directory (Dir); end if; Ada.Directories.Create_Directory (Path); Generator.Set_Result_Directory (Path); -- Create the plugin project instance and generate its dynamo.xml file. -- The new plugin is added to the current project so that it will be referenced. declare procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition); procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is Plugin : Gen.Model.Projects.Project_Definition_Access; File : constant String := Util.Files.Compose (Path, "dynamo.xml"); begin Project.Create_Project (Name => Name, Path => File, Project => Plugin); Project.Add_Module (Plugin); Plugin.Props.Set ("license", Project.Props.Get ("license", "none")); Plugin.Props.Set ("author", Project.Props.Get ("author", "")); Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", "")); Plugin.Save (File); end Create_Plugin; begin Generator.Update_Project (Create_Plugin'Access); end; -- Generate the new plugin content. Generator.Set_Force_Save (False); Generator.Set_Global ("pluginName", Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin"); if Kind /= "" then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin-" & Kind); end if; -- And save the project dynamo.xml file which now refers to the new plugin. Generator.Set_Result_Directory (Result_Dir); Generator.Save_Project; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-plugin: Create a new plugin for the current project"); Put_Line ("Usage: create-plugin NAME"); New_Line; Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME."); end Help; end Gen.Commands.Plugins;
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with Gen.Model.Projects; with GNAT.Command_Line; with Util.Files; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Plugins is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Result_Dir : constant String := Generator.Get_Result_Directory; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l:") is when ASCII.NUL => exit; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; declare Name : constant String := Get_Argument; Kind : constant String := Get_Argument; Dir : constant String := Generator.Get_Plugin_Directory; Path : constant String := Util.Files.Compose (Dir, Name); begin if Name'Length = 0 then Generator.Error ("Missing plugin name"); Gen.Commands.Usage; return; end if; if Kind /= "ada" and Kind /= "web" and Kind /= "" then Generator.Error ("Invalid plugin type (must be 'ada' or 'web')"); return; end if; if Ada.Directories.Exists (Path) then Generator.Error ("Plugin {0} exists already", Name); return; end if; if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Directory (Dir); end if; Ada.Directories.Create_Directory (Path); Generator.Set_Result_Directory (Path); -- Create the plugin project instance and generate its dynamo.xml file. -- The new plugin is added to the current project so that it will be referenced. declare procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition); procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is Plugin : Gen.Model.Projects.Project_Definition_Access; File : constant String := Util.Files.Compose (Path, "dynamo.xml"); begin Project.Create_Project (Name => Name, Path => File, Project => Plugin); Project.Add_Module (Plugin); Plugin.Props.Set ("license", Project.Props.Get ("license", "none")); Plugin.Props.Set ("author", Project.Props.Get ("author", "")); Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", "")); Plugin.Save (File); end Create_Plugin; begin Generator.Update_Project (Create_Plugin'Access); end; -- Generate the new plugin content. Generator.Set_Force_Save (False); Generator.Set_Global ("pluginName", Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin"); if Kind /= "" then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin-" & Kind); end if; -- And save the project dynamo.xml file which now refers to the new plugin. Generator.Set_Result_Directory (Result_Dir); Generator.Save_Project; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-plugin: Create a new plugin for the current project"); Put_Line ("Usage: create-plugin NAME [ada | web]"); New_Line; Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME."); Put_Line (" The plugin type is specified as the last argument which can be one of:"); New_Line; Put_Line (" ada the plugin contains Ada code and a GNAT project is created"); Put_Line (" web the plugin contains XHTML, CSS, Javascript files only"); New_Line; Put_Line (" The plugin is created in the directory:"); Put_Line (" plugins/NAME"); end Help; end Gen.Commands.Plugins;
Update the documentation for the help create-plugin command
Update the documentation for the help create-plugin command
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
c44636eef7002c239dde452cab4d5ae3bfc2f16e
src/gen-commands-propset.ads
src/gen-commands-propset.ads
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Propset is -- ------------------------------ -- Propset Command -- ------------------------------ -- This command sets a property in the dynamo project configuration. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Propset;
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Propset is -- ------------------------------ -- Propset Command -- ------------------------------ -- This command sets a property in the dynamo project configuration. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Propset;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
e07467a0f93904dfd98e758a0d26fac50b119287
src/asf-components-utils-escapes.adb
src/asf-components-utils-escapes.adb
----------------------------------------------------------------------- -- components-utils-escape -- Escape generated content produced by component children -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; package body ASF.Components.Utils.Escapes is -- ------------------------------ -- Write the content that was collected by rendering the inner children. -- Escape the content using Javascript escape rules. -- ------------------------------ procedure Write_Content (UI : in UIEscape; Writer : in out Contexts.Writer.Response_Writer'Class; Content : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI, Context); Result : Ada.Strings.Unbounded.Unbounded_String; begin Util.Strings.Transforms.Escape_Java (Content => Content, Into => Result); Writer.Write (Result); end Write_Content; -- ------------------------------ -- Encode the children components in the javascript queue. -- ------------------------------ overriding procedure Encode_Children (UI : in UIEscape; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin UIEscape'Class (UI).Write_Content (Writer.all, Content, Context); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; end ASF.Components.Utils.Escapes;
----------------------------------------------------------------------- -- components-utils-escape -- Escape generated content produced by component children -- Copyright (C) 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; package body ASF.Components.Utils.Escapes is -- ------------------------------ -- Write the content that was collected by rendering the inner children. -- Escape the content using Javascript escape rules. -- ------------------------------ procedure Write_Content (UI : in UIEscape; Writer : in out Contexts.Writer.Response_Writer'Class; Content : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI, Context); Result : Ada.Strings.Unbounded.Unbounded_String; Mode : constant String := UI.Get_Attribute (ESCAPE_MODE_NAME, Context); begin if Mode = "xml" then Util.Strings.Transforms.Escape_Xml (Content => Content, Into => Result); else Util.Strings.Transforms.Escape_Java (Content => Content, Into => Result); end if; Writer.Write (Result); end Write_Content; -- ------------------------------ -- Encode the children components in the javascript queue. -- ------------------------------ overriding procedure Encode_Children (UI : in UIEscape; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin UIEscape'Class (UI).Write_Content (Writer.all, Content, Context); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; end ASF.Components.Utils.Escapes;
Add support to escape using XML or using Javascript escape rules
Add support to escape using XML or using Javascript escape rules
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
cf41feb945a4a2b82e369730b0ac94659a9de688
examples/ada/x12a.adb
examples/ada/x12a.adb
-- $Id$ -- Simple line plot and multiple windows demo. -- Copyright (C) 2007 Werner Smekal -- This file is part of PLplot. -- PLplot is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Library Public License as published -- by the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- PLplot is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Library General Public License for more details. -- You should have received a copy of the GNU Library General Public License -- along with PLplot; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA with Interfaces.C, Ada.Text_IO, Ada.Numerics, Ada.Numerics.Long_Elementary_Functions, Ada.Strings.Bounded, PLplot, PlplotThin; use Interfaces.C, Ada.Text_IO, Ada.Numerics, Ada.Numerics.Long_Elementary_Functions, Ada.Strings.Bounded, PLplot, PlplotThin; -- COMMENT THIS LINE IF YOUR COMPILER DOES NOT INCLUDE THESE -- DEFINITIONS, FOR EXAMPLE, IF IT IS NOT ADA 2005 WITH ANNEX G.3 COMPLIANCE. --with Ada.Numerics.Long_Real_Arrays; use Ada.Numerics.Long_Real_Arrays; procedure x12a is string : char_array(0 .. 20); y0 : PL_Float_Array (0 .. 9); procedure Sprintf( buffer : out char_array; format : in char_array; variable: in PLFLT ); pragma Import(C, Sprintf, "sprintf" ); procedure plfbox(x0 : PLFLT; y0 : PLFLT) is x, y : PL_Float_Array (0 .. 3); begin x(0) := x0; y(0) := 0.0; x(1) := x0; y(1) := y0; x(2) := x0 + 1.0; y(2) := y0; x(3) := x0 + 1.0; y(3) := 0.0; plfill(4, x, y); plcol0(1); pllsty(1); plline(4, x, y); end; begin -- plplot initialization -- plparseopts(PL_PARSE_FULL); Parse_Command_Line_Arguments(PL_PARSE_FULL); plinit; pladv(0); plvsta; plwind(1980.0, 1990.0, 0.0, 35.0); plbox("bc" & Nul, 1.0, 0, "bcnv" & Nul, 10.0, 0); plcol0(2); pllab("Year" & Nul, "Widget Sales (millions)" & Nul, "#frPLplot Example 12" & Nul); y0(0) := 5.0; y0(1) := 15.0; y0(2) := 12.0; y0(3) := 24.0; y0(4) := 28.0; y0(5) := 30.0; y0(6) := 20.0; y0(7) := 8.0; y0(8) := 12.0; y0(9) := 3.0; for i in y0'Range loop plcol0(i + 1); plpsty(0); plfbox(Long_Float(1980 + i), y0(i)); sprintf(string, "%.0f" & Nul, y0(i)); plptex(Long_Float(1980 + i) + 0.5, (y0(i) + 1.0), 1.0, 0.0, 0.5, string); sprintf(string, "%.0f" & Nul, Long_Float(1980 + i)); plmtex("b" & Nul, 1.0, (Long_Float(i + 1) * 0.1 - 0.05), 0.5, string); end loop; -- Don't forget to call plend() to finish off! plend; end x12a;
-- $Id$ -- Simple line plot and multiple windows demo. -- Copyright (C) 2007 Werner Smekal -- This file is part of PLplot. -- PLplot is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Library Public License as published -- by the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- PLplot is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Library General Public License for more details. -- You should have received a copy of the GNU Library General Public License -- along with PLplot; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA with Ada.Text_IO, Ada.Numerics, Ada.Numerics.Long_Elementary_Functions, Ada.Strings.Bounded, Interfaces.C, PlplotThin; use Ada.Text_IO, Ada.Numerics, Ada.Numerics.Long_Elementary_Functions, Ada.Strings.Bounded, Interfaces.C, PlplotThin; -- COMMENT THIS LINE IF YOUR COMPILER DOES NOT INCLUDE THESE -- DEFINITIONS, FOR EXAMPLE, IF IT IS NOT ADA 2005 WITH ANNEX G.3 COMPLIANCE. --with Ada.Numerics.Long_Real_Arrays; use Ada.Numerics.Long_Real_Arrays; procedure x12a is string : char_array(0 .. 20); y0 : PL_Float_Array (0 .. 9); procedure Sprintf( buffer : out char_array; format : in char_array; variable: in PLFLT ); pragma Import(C, Sprintf, "sprintf" ); procedure plfbox(x0 : PLFLT; y0 : PLFLT) is x, y : PL_Float_Array (0 .. 3); begin x(0) := x0; y(0) := 0.0; x(1) := x0; y(1) := y0; x(2) := x0 + 1.0; y(2) := y0; x(3) := x0 + 1.0; y(3) := 0.0; plfill(4, x, y); plcol0(1); pllsty(1); plline(4, x, y); end; begin -- plplot initialization plparseopts(PL_PARSE_FULL); plinit; pladv(0); plvsta; plwind(1980.0, 1990.0, 0.0, 35.0); plbox(To_C("bc"), 1.0, 0, To_C("bcnv"), 10.0, 0); plcol0(2); pllab(To_C("Year"), To_C("Widget Sales (millions)"), To_C("#frPLplot Example 12")); y0(0) := 5.0; y0(1) := 15.0; y0(2) := 12.0; y0(3) := 24.0; y0(4) := 28.0; y0(5) := 30.0; y0(6) := 20.0; y0(7) := 8.0; y0(8) := 12.0; y0(9) := 3.0; for i in y0'Range loop plcol0(i + 1); plpsty(0); plfbox(Long_Float(1980 + i), y0(i)); sprintf(string, To_C("%.0f"), y0(i)); plptex(Long_Float(1980 + i) + 0.5, (y0(i) + 1.0), 1.0, 0.0, 0.5, string); sprintf(string, To_C("%.0f"), Long_Float(1980 + i)); plmtex(To_C("b"), 1.0, (Long_Float(i + 1) * 0.1 - 0.05), 0.5, string); end loop; -- Don't forget to call plend() to finish off! plend; end x12a;
Use of To_C for all strings, whitespace changes, move to pure thin API (plparseopts). Result (with plfill library changes just committed) is identical to C example.
Use of To_C for all strings, whitespace changes, move to pure thin API (plparseopts). Result (with plfill library changes just committed) is identical to C example. svn path=/trunk/; revision=7443
Ada
lgpl-2.1
FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot
e9b7c6053badc05b291e224515552e3a08a88a75
matp/src/mat-commands.ads
matp/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Events command. -- Print the probe events. procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Event command. -- Print the probe event with the stack frame. procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Info command to print symmary information about the program. procedure Info_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Timeline command. -- Identify the interesting timeline groups in the events and display them. procedure Timeline_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Events command. -- Print the probe events. procedure Events_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Event command. -- Print the probe event with the stack frame. procedure Event_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Info command to print symmary information about the program. procedure Info_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Timeline command. -- Identify the interesting timeline groups in the events and display them. procedure Timeline_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Addr command to print a description of an address. procedure Addr_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Declare the Addr_Command procedure
Declare the Addr_Command procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b72d379b149ee6d7e2d3ea1ad9a9cbb3afc4e95d
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Wide_Wide_Hash; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Wiki.Strings; with ASF.Helpers.Beans; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Events; with AWA.Components.Wikis; -- == Ada Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_IMAGE_ATTR : constant String := "image"; POST_DESCRIPTION_ATTR : constant String := "description"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; COUNTER_ATTR : constant String := "counter"; use Ada.Strings.Wide_Wide_Unbounded; -- Get a select item list which contains a list of blog post formats. function Create_Format_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; package Image_Info_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Models.Image_Info, Hash => Ada.Strings.Wide_Wide_Hash, Equivalent_Keys => "=", "=" => Models."="); type Post_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Post_Id : ADO.Identifier; Images : Image_Info_Maps.Map; end record; procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; Info : in AWA.Blogs.Models.Image_Info; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); procedure Find_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the blog information. overriding procedure Load (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Handle an event to create the blog entry automatically. overriding procedure Create_Default (Bean : in out Blog_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Blog_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Blog_Bean, Element_Access => Blog_Bean_Access); -- ------------------------------ -- Post Bean -- ------------------------------ -- The <b>Post_Bean</b> is used to create, update or display a post associated with a blog. type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The post description generated from the content. Description : Ada.Strings.Unbounded.Unbounded_String; Image_Link : Wiki.Strings.UString; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Build the URI from the post title and the post date. function Get_Predefined_Uri (Title : in String; Date : in Ada.Calendar.Time) return String; -- Make the post description from the summary or the content. procedure Make_Description (From : in out Post_Bean); -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the public display. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Setup the bean to create a new post. overriding procedure Setup (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the administrator. overriding procedure Load_Admin (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI either with visible comments or with all comments. procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String; Publish_Only : in Boolean); -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post List Bean -- ------------------------------ -- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : access Post_Links_Bean; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the -- list of posts that are created, published or not. type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Blog Statistics Bean -- ------------------------------ -- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post. type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean; Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access; end record; type Blog_Stat_Bean_Access is access all Blog_Stat_Bean; overriding function Get_Value (List : in Blog_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Blog_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Wide_Wide_Hash; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Wiki.Strings; with Wiki.Plugins.Conditions; with Wiki.Plugins.Variables; with ASF.Helpers.Beans; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Events; with AWA.Components.Wikis; -- == Ada Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_IMAGE_ATTR : constant String := "image"; POST_DESCRIPTION_ATTR : constant String := "description"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; COUNTER_ATTR : constant String := "counter"; use Ada.Strings.Wide_Wide_Unbounded; -- Get a select item list which contains a list of blog post formats. function Create_Format_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; package Image_Info_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Models.Image_Info, Hash => Ada.Strings.Wide_Wide_Hash, Equivalent_Keys => "=", "=" => Models."="); type Post_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Post_Id : ADO.Identifier; Images : Image_Info_Maps.Map; end record; procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; Info : in AWA.Blogs.Models.Image_Info; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); procedure Find_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the blog information. overriding procedure Load (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Handle an event to create the blog entry automatically. overriding procedure Create_Default (Bean : in out Blog_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Blog_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Blog_Bean, Element_Access => Blog_Bean_Access); -- ------------------------------ -- Post Bean -- ------------------------------ -- The <b>Post_Bean</b> is used to create, update or display a post associated with a blog. type Post_Bean is new AWA.Blogs.Models.Post_Bean and Wiki.Plugins.Plugin_Factory with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- Condition plugin. Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; -- Variable plugin. Variable : aliased Wiki.Plugins.Variables.Variable_Plugin; -- The post description generated from the content. Description : Ada.Strings.Unbounded.Unbounded_String; Image_Link : Wiki.Strings.UString; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Build the URI from the post title and the post date. function Get_Predefined_Uri (Title : in String; Date : in Ada.Calendar.Time) return String; -- Make the post description from the summary or the content. procedure Make_Description (From : in out Post_Bean); -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Find a plugin knowing its name. overriding function Find (Factory : in Post_Bean; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access; -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the public display. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Setup the bean to create a new post. overriding procedure Setup (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the administrator. overriding procedure Load_Admin (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI either with visible comments or with all comments. procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String; Publish_Only : in Boolean); -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post List Bean -- ------------------------------ -- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : access Post_Links_Bean; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the -- list of posts that are created, published or not. type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Blog Statistics Bean -- ------------------------------ -- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post. type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean; Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access; end record; type Blog_Stat_Bean_Access is access all Blog_Stat_Bean; overriding function Get_Value (List : in Blog_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Blog_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
Add the condition and variables plugin when rendering a blog post
Add the condition and variables plugin when rendering a blog post
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a9fc8d18dcc847388bf478dab886a77a9235a589
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; end Security.Permissions;
Document the permission
Document the permission
Ada
apache-2.0
Letractively/ada-security
343683e7edf22aa3e28922535241c3d5963ce38e
src/util-strings-transforms.ads
src/util-strings-transforms.ads
----------------------------------------------------------------------- -- Util-texts -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Texts.Transforms; with Ada.Strings.Unbounded; with Ada.Characters.Handling; package Util.Strings.Transforms is pragma Preelaborate; use Ada.Strings.Unbounded; package TR is new Util.Texts.Transforms (Stream => Unbounded_String, Char => Character, Input => String, Put => Ada.Strings.Unbounded.Append, To_Upper => Ada.Characters.Handling.To_Upper, To_Lower => Ada.Characters.Handling.To_Lower, To_Input => Ada.Strings.Unbounded.To_String); -- Capitalize the string into the result stream. procedure Capitalize (Content : in String; Into : in out Unbounded_String) renames TR.Capitalize; function Capitalize (Content : String) return String renames TR.Capitalize; -- Translate the input string into an upper case string in the result stream. procedure To_Upper_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Upper_Case; function To_Upper_Case (Content : String) return String renames TR.To_Upper_Case; -- Translate the input string into a lower case string in the result stream. procedure To_Lower_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Lower_Case; function To_Lower_Case (Content : String) return String renames TR.To_Lower_Case; -- Escape the content into the result stream using the JavaScript -- escape rules. procedure Escape_Javascript (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java_Script; function Escape_Javascript (Content : String) return String renames TR.Escape_Java_Script; -- Escape the content into the result stream using the Java -- escape rules. procedure Escape_Java (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java; function Escape_Java (Content : String) return String renames TR.Escape_Java; -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 procedure Escape_Xml (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Xml; function Escape_Xml (Content : String) return String renames TR.Escape_Xml; end Util.Strings.Transforms;
----------------------------------------------------------------------- -- Util-texts -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Texts.Transforms; with Ada.Strings.Unbounded; with Ada.Characters.Handling; package Util.Strings.Transforms is pragma Preelaborate; use Ada.Strings.Unbounded; package TR is new Util.Texts.Transforms (Stream => Unbounded_String, Char => Character, Input => String, Put => Ada.Strings.Unbounded.Append, To_Upper => Ada.Characters.Handling.To_Upper, To_Lower => Ada.Characters.Handling.To_Lower, To_Input => Ada.Strings.Unbounded.To_String); -- Capitalize the string into the result stream. procedure Capitalize (Content : in String; Into : in out Unbounded_String) renames TR.Capitalize; function Capitalize (Content : String) return String renames TR.Capitalize; -- Translate the input string into an upper case string in the result stream. procedure To_Upper_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Upper_Case; function To_Upper_Case (Content : String) return String renames TR.To_Upper_Case; -- Translate the input string into a lower case string in the result stream. procedure To_Lower_Case (Content : in String; Into : in out Unbounded_String) renames TR.To_Lower_Case; function To_Lower_Case (Content : String) return String renames TR.To_Lower_Case; -- Write in the output stream the value as a \uNNNN encoding form. procedure To_Hex (Into : in out Unbounded_String; Value : in Character) renames TR.To_Hex; -- Escape the content into the result stream using the JavaScript -- escape rules. procedure Escape_Javascript (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java_Script; function Escape_Javascript (Content : String) return String renames TR.Escape_Java_Script; -- Escape the content into the result stream using the Java -- escape rules. procedure Escape_Java (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Java; function Escape_Java (Content : String) return String renames TR.Escape_Java; -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 procedure Escape_Xml (Content : in String; Into : in out Unbounded_String) renames TR.Escape_Xml; function Escape_Xml (Content : String) return String renames TR.Escape_Xml; end Util.Strings.Transforms;
Add the To_Hex procedure
Add the To_Hex procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
dc191fbf8ee954ab0b5a87e569a070a424b1eeb5
src/util-properties-json.adb
src/util-properties-json.adb
----------------------------------------------------------------------- -- util-properties-json -- read json files into properties -- 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.Serialize.IO.JSON; with Util.Stacks; with Util.Beans.Objects; package body Util.Properties.JSON is type Natural_Access is access all Natural; package Length_Stack is new Util.Stacks (Element_Type => Natural, Element_Type_Access => Natural_Access); type Parser is new Util.Serialize.IO.JSON.Parser with record Base_Name : Ada.Strings.Unbounded.Unbounded_String; Lengths : Length_Stack.Stack; Separator : Ada.Strings.Unbounded.Unbounded_String; Separator_Length : Natural; end record; -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. overriding procedure Start_Object (Handler : in out Parser; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. overriding procedure Finish_Object (Handler : in out Parser; Name : in String); -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Parser; Name : in String) is begin if Name'Length > 0 then Ada.Strings.Unbounded.Append (Handler.Base_Name, Name); Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator); Length_Stack.Push (Handler.Lengths); Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length; end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Parser; Name : in String) is Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name); begin if Name'Length > 0 then Ada.Strings.Unbounded.Delete (Handler.Base_Name, Len - Name'Length - Handler.Separator_Length + 1, Len); end if; end Finish_Object; -- ----------------------- -- Parse the JSON content and put the flattened content in the property manager. -- ----------------------- procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class; Content : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with record Manager : access Util.Properties.Manager'Class; end record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; begin P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Manager := Manager'Access; P.Parse_String (Content); if P.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Parse_JSON; -- ----------------------- -- Read the JSON file into the property manager. -- The JSON content is flatten into Flatten the JSON content and add the properties. -- ----------------------- procedure Read_JSON (Manager : in out Util.Properties.Manager'Class; Path : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with record Manager : access Util.Properties.Manager'Class; end record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; begin P.Manager := Manager'Access; P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Parse (Path); if P.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Read_JSON; end Util.Properties.JSON;
----------------------------------------------------------------------- -- util-properties-json -- read json files into properties -- Copyright (C) 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.Serialize.IO.JSON; with Util.Stacks; with Util.Beans.Objects; package body Util.Properties.JSON is type Natural_Access is access all Natural; package Length_Stack is new Util.Stacks (Element_Type => Natural, Element_Type_Access => Natural_Access); type Parser is new Util.Serialize.IO.JSON.Parser with record Base_Name : Ada.Strings.Unbounded.Unbounded_String; Lengths : Length_Stack.Stack; Separator : Ada.Strings.Unbounded.Unbounded_String; Separator_Length : Natural; end record; -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. overriding procedure Start_Object (Handler : in out Parser; Name : in String); -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. overriding procedure Finish_Object (Handler : in out Parser; Name : in String); overriding procedure Start_Array (Handler : in out Parser; Name : in String); overriding procedure Finish_Array (Handler : in out Parser; Name : in String); -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Parser; Name : in String) is begin if Name'Length > 0 then Ada.Strings.Unbounded.Append (Handler.Base_Name, Name); Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator); Length_Stack.Push (Handler.Lengths); Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length; end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Parser; Name : in String) is Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name); begin if Name'Length > 0 then Ada.Strings.Unbounded.Delete (Handler.Base_Name, Len - Name'Length - Handler.Separator_Length + 1, Len); end if; end Finish_Object; overriding procedure Start_Array (Handler : in out Parser; Name : in String) is begin Handler.Start_Object (Name); Util.Serialize.IO.JSON.Parser (Handler).Start_Array (Name); end Start_Array; overriding procedure Finish_Array (Handler : in out Parser; Name : in String) is begin Handler.Finish_Object (Name); Util.Serialize.IO.JSON.Parser (Handler).Finish_Array (Name); end Finish_Array; -- ----------------------- -- Parse the JSON content and put the flattened content in the property manager. -- ----------------------- procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class; Content : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with record Manager : access Util.Properties.Manager'Class; end record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; begin P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Manager := Manager'Access; P.Parse_String (Content); if P.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Parse_JSON; -- ----------------------- -- Read the JSON file into the property manager. -- The JSON content is flatten into Flatten the JSON content and add the properties. -- ----------------------- procedure Read_JSON (Manager : in out Util.Properties.Manager'Class; Path : in String; Flatten_Separator : in String := ".") is type Local_Parser is new Parser with record Manager : access Util.Properties.Manager'Class; end record; -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False); -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Local_Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); begin Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name, Util.Beans.Objects.To_String (Value)); end Set_Member; P : Local_Parser; begin P.Manager := Manager'Access; P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator); P.Separator_Length := Flatten_Separator'Length; P.Parse (Path); if P.Has_Error then raise Util.Serialize.IO.Parse_Error; end if; end Read_JSON; end Util.Properties.JSON;
Fix the json to properties parser to use the array index for some elements in arrays
Fix the json to properties parser to use the array index for some elements in arrays
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e934ad99af342c778fd12f2302fbc4565b327fa4
src/wiki-parsers-textile.adb
src/wiki-parsers-textile.adb
----------------------------------------------------------------------- -- wiki-parsers-textile -- Textile parser operations -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Nodes; with Wiki.Helpers; package body Wiki.Parsers.Textile is use Wiki.Helpers; use Wiki.Nodes; -- ------------------------------ -- Parse a textile wiki heading in the form 'h<N>.'. -- Example: -- h1. Level 1 -- h2. Level 2 -- ------------------------------ procedure Parse_Header (P : in out Parser; Token : in Wiki.Strings.WChar) is procedure Add_Header (Content : in Wiki.Strings.WString); C : Wiki.Strings.WChar; C2 : Wiki.Strings.WChar; Level : Integer := 1; procedure Add_Header (Content : in Wiki.Strings.WString) is Last : Natural := Content'Last; Ignore_Token : Boolean := True; Seen_Token : Boolean := False; begin -- Remove the spaces and '=' at end of header string. while Last > Content'First loop if Content (Last) = Token then exit when not Ignore_Token; Seen_Token := True; elsif Content (Last) = ' ' or Content (Last) = HT then Ignore_Token := not Seen_Token; else exit; end if; Last := Last - 1; end loop; P.Context.Filters.Add_Header (P.Document, Content (Content'First .. Last), Level); end Add_Header; procedure Add_Header is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Header); begin if not P.Empty_Line then Parse_Text (P, Token); return; end if; Peek (P, C); case C is when '1' => Level := 1; when '2' => Level := 2; when '3' => Level := 3; when '4' => Level := 4; when '5' => Level := 5; when others => Parse_Text (P, Token); Parse_Text (P, C); return; end case; Peek (P, C2); if C2 /= '.' then Parse_Text (P, Token); Parse_Text (P, C); Parse_Text (P, C2); return; end if; -- Ignore spaces after the hN. sequence Peek (P, C); while C = ' ' or C = HT loop Peek (P, C); end loop; Flush_Text (P); Flush_List (P); loop Append (P.Text, C); Peek (P, C); exit when C = LF or C = CR; end loop; if not P.Context.Is_Hidden then Add_Header (P.Text); end if; P.Empty_Line := True; P.In_Paragraph := False; Clear (P.Text); end Parse_Header; -- Parse a textile image. -- Example: -- !image-link! -- !image-link(title)! -- !image-path|:http-link procedure Parse_Image (P : in out Parser; Token : in Wiki.Strings.WChar) is begin null; end Parse_Image; -- Parse an external link: -- Example: -- "title":http-link procedure Parse_Link (P : in out Parser; Token : in Wiki.Strings.WChar) is begin null; end Parse_Link; -- Parse an italic or bold sequence or a list. -- Example: -- *name* (italic) -- **name** (bold) -- * item (list) procedure Parse_Bold_Or_List (P : in out Parser; Token : in Wiki.Strings.WChar) is begin null; end Parse_Bold_Or_List; -- Parse a markdown table/column. -- Example: -- | col1 | col2 | ... | colN | procedure Parse_Table (P : in out Parser; Token : in Wiki.Strings.WChar) is begin null; end Parse_Table; procedure Parse_Deleted_Or_Horizontal_Rule (P : in out Parser; Token : in Wiki.Strings.WChar) is begin null; end Parse_Deleted_Or_Horizontal_Rule; end Wiki.Parsers.Textile;
----------------------------------------------------------------------- -- wiki-parsers-textile -- Textile parser operations -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Nodes; with Wiki.Helpers; package body Wiki.Parsers.Textile is use Wiki.Helpers; use Wiki.Nodes; -- ------------------------------ -- Parse a textile wiki heading in the form 'h<N>.'. -- Example: -- h1. Level 1 -- h2. Level 2 -- ------------------------------ procedure Parse_Header (P : in out Parser; Token : in Wiki.Strings.WChar) is procedure Add_Header (Content : in Wiki.Strings.WString); C : Wiki.Strings.WChar; C2 : Wiki.Strings.WChar; Level : Integer := 1; procedure Add_Header (Content : in Wiki.Strings.WString) is Last : Natural := Content'Last; Ignore_Token : Boolean := True; Seen_Token : Boolean := False; begin -- Remove the spaces and '=' at end of header string. while Last > Content'First loop if Content (Last) = Token then exit when not Ignore_Token; Seen_Token := True; elsif Content (Last) = ' ' or Content (Last) = HT then Ignore_Token := not Seen_Token; else exit; end if; Last := Last - 1; end loop; P.Context.Filters.Add_Header (P.Document, Content (Content'First .. Last), Level); end Add_Header; procedure Add_Header is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Header); begin if not P.Empty_Line then Parse_Text (P, Token); return; end if; Peek (P, C); case C is when '1' => Level := 1; when '2' => Level := 2; when '3' => Level := 3; when '4' => Level := 4; when '5' => Level := 5; when others => Parse_Text (P, Token); Parse_Text (P, C); return; end case; Peek (P, C2); if C2 /= '.' then Parse_Text (P, Token); Parse_Text (P, C); Parse_Text (P, C2); return; end if; -- Ignore spaces after the hN. sequence Peek (P, C); while C = ' ' or C = HT loop Peek (P, C); end loop; Flush_Text (P); Flush_List (P); loop Append (P.Text, C); Peek (P, C); exit when C = LF or C = CR; end loop; if not P.Context.Is_Hidden then Add_Header (P.Text); end if; P.Empty_Line := True; P.In_Paragraph := False; Clear (P.Text); end Parse_Header; -- ------------------------------ -- Parse a textile image. -- Example: -- !image-link! -- !image-link(title)! -- !image-path!:http-link -- ------------------------------ procedure Parse_Image (P : in out Parser; Token : in Wiki.Strings.WChar) is Pos : Natural := P.Line_Pos + 1; Last : Natural; C : Wiki.Strings.WChar; begin Last := Wiki.Strings.Index (P.Line, '!', Pos); if Last = 0 then Append (P.Text, Token); return; end if; declare Title : Wiki.Strings.UString; Link : Wiki.Strings.UString; Title_Pos : Natural; Last_Pos : Natural; begin Title_Pos := Wiki.Strings.Index (P.Line, '(', Pos); if Title_Pos = 0 then Last_Pos := Last; else Last_Pos := Title_Pos; end if; while Pos < Last_Pos loop Wiki.Strings.Append (Link, Wiki.Strings.Element (P.Line, Pos)); Pos := Pos + 1; end loop; if Title_Pos > 0 then Title_Pos := Title_Pos + 1; while Title_Pos < Last - 1 loop Wiki.Strings.Append (Title, Wiki.Strings.Element (P.Line, Title_Pos)); Title_Pos := Title_Pos + 1; end loop; end if; Flush_Text (P); P.Line_Pos := Last; if not P.Context.Is_Hidden then Wiki.Attributes.Clear (P.Attributes); Wiki.Attributes.Append (P.Attributes, "src", Link); P.Context.Filters.Add_Image (P.Document, Wiki.Strings.To_WString (Title), P.Attributes); end if; end; end Parse_Image; -- Parse an external link: -- Example: -- "title":http-link procedure Parse_Link (P : in out Parser; Token : in Wiki.Strings.WChar) is Pos : Natural := P.Line_Pos; Next : Natural := Wiki.Strings.Index (P.Line, Token, Pos); C : Wiki.Strings.WChar; begin if Next = 0 or Next = P.Line_Length then Append (P.Text, Token); return; end if; C := Wiki.Strings.Element(P.Line, Next + 1); if C /= ':' then Append (P.Text, Token); return; end if; Flush_Text (P); Wiki.Attributes.Clear (P.Attributes); P.Empty_Line := False; if not P.Context.Is_Hidden then declare Link : constant Strings.WString := Attributes.Get_Attribute (P.Attributes, HREF_ATTR); Name : constant Strings.WString := Attributes.Get_Attribute (P.Attributes, NAME_ATTR); begin P.Context.Filters.Add_Link (P.Document, Name, P.Attributes); end; end if; end Parse_Link; -- ------------------------------ -- Parse a bold sequence or a list. -- Example: -- *name* (bold) -- * item (list) -- ------------------------------ procedure Parse_Bold_Or_List (P : in out Parser; Token : in Wiki.Strings.WChar) is C : Wiki.Strings.WChar; begin Peek (P, C); if P.Empty_Line and C = ' ' then Put_Back (P, C); Common.Parse_List (P, Token); return; end if; Put_Back (P, C); Toggle_Format (P, BOLD); end Parse_Bold_Or_List; -- Parse a markdown table/column. -- Example: -- | col1 | col2 | ... | colN | procedure Parse_Table (P : in out Parser; Token : in Wiki.Strings.WChar) is begin null; end Parse_Table; procedure Parse_Deleted_Or_Horizontal_Rule (P : in out Parser; Token : in Wiki.Strings.WChar) is begin null; end Parse_Deleted_Or_Horizontal_Rule; end Wiki.Parsers.Textile;
Implement the Parse_Image, Parse_Bold_Or_List and Parse_Link
Implement the Parse_Image, Parse_Bold_Or_List and Parse_Link
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
8e419b64deed621455d52814a02bd9b13012e62f
src/wiki-attributes.ads
src/wiki-attributes.ads
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- === Attributes === -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. 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; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString; -- 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.UString; -- 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 Wiki.Strings.UString; Value : in Wiki.Strings.UString); -- 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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 <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List</tt> -- with some operations to append or query for an attribute. 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;
Remove Get_Unbounded_Wide_Value, Append and Get_Attribute operation
Remove Get_Unbounded_Wide_Value, Append and Get_Attribute operation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d56771ee1b7db043fe1d69d4b7b82345879ae147
src/asf-security-servlets.ads
src/asf-security-servlets.ads
----------------------------------------------------------------------- -- security-openid-servlets - Servlets for OpenID 2.0 Authentication -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Servlets; with ASF.Requests; with ASF.Responses; with ASF.Principals; with Security.Auth; use Security; -- The <b>Security.Openid.Servlets</b> package defines two servlets that can be used -- to implement an OpenID 2.0 authentication with an OpenID provider such as Google, -- Yahoo!, Verisign, Orange, ... -- -- The process to use these servlets is the following: -- <ul> -- <li>Declare and register a <b>Request_Auth_Servlet</b> servlet.</li> -- <li>Map that servlet to an authenticate URL. To authenticate, a user will have -- to click on a link mapped to that servlet. To identify the OpenID provider, -- the URL must contain the name of the provider. Example: -- -- http://localhost:8080/app/openid/auth/google -- -- <li>Declare and register a <b>Verify_Auth_Servlet</b> servlet. -- <li>Map that servlet to the verification URL. This is the URL that the user -- will return to when authentication is done by the OpenID provider. Example: -- -- http://localhost:8080/app/openid/verify -- -- <li>Declare in the application properties a set of configurations: -- <ul> -- <li>The <b>openid.realm</b> must indicate the URL that identifies the -- application the end user will trust. Example: -- -- openid.realm=http://localhost:8080/app -- -- <li>The <b>openid.callback_url</b> must indicate the callback URL to -- which the OpenID provider will redirect the user when authentication -- is finished (successfully or not). The callback URL must match -- the realm. -- -- openid.callback_url=http://localhost:8080/app/openid/verify -- -- <li>For each OpenID provider, a URL to the Yadis entry point of the -- OpenID provider is necessary. This URL is used to get the XRDS -- stream giving endoint of the OpenID provider. Example: -- -- openid.provider.google=https://www.google.com/accounts/o8/id -- </ul> -- -- </ul> -- package ASF.Security.Servlets is -- ------------------------------ -- OpenID Servlet -- ------------------------------ -- The <b>Openid_Servlet</b> is the OpenID root servlet for OpenID 2.0 authentication. -- It is defined to provide a common basis for the authentication and verification servlets. type Openid_Servlet is abstract new ASF.Servlets.Servlet and Auth.Parameters 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 Openid_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class); -- Get a configuration parameter from the servlet context for the security Auth provider. overriding function Get_Parameter (Server : in Openid_Servlet; Name : in String) return String; -- ------------------------------ -- OpenID Request Servlet -- ------------------------------ -- The <b>Request_Auth_Servlet</b> servlet implements the first steps of an OpenID -- authentication. type Request_Auth_Servlet is new Openid_Servlet with private; -- Proceed to the OpenID authentication with an OpenID provider. -- Find the OpenID provider URL and starts the discovery, association phases -- during which a private key is obtained from the OpenID provider. -- After OpenID discovery and association, the user will be redirected to -- the OpenID provider. overriding procedure Do_Get (Server : in Request_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- ------------------------------ -- OpenID Verification Servlet -- ------------------------------ -- The <b>Verify_Auth_Servlet</b> verifies the authentication result and -- extract authentication from the callback URL. type Verify_Auth_Servlet is new Openid_Servlet with private; -- Verify the authentication result that was returned by the OpenID provider. -- If the authentication succeeded and the signature was correct, sets a -- user principals on the session. overriding procedure Do_Get (Server : in Verify_Auth_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Create a principal object that correspond to the authenticated user identified -- by the <b>Credential</b> information. The principal will be attached to the session -- and will be destroyed when the session is closed. procedure Create_Principal (Server : in Verify_Auth_Servlet; Credential : in Auth.Authentication; Result : out ASF.Principals.Principal_Access); private function Get_Provider_URL (Server : in Request_Auth_Servlet; Request : in ASF.Requests.Request'Class) return String; procedure Initialize (Server : in Openid_Servlet; Provider : in String; Manager : in out Auth.Manager); type Openid_Servlet is new ASF.Servlets.Servlet and Auth.Parameters with null record; type Request_Auth_Servlet is new Openid_Servlet with null record; type Verify_Auth_Servlet is new Openid_Servlet with null record; end ASF.Security.Servlets;
----------------------------------------------------------------------- -- security-openid-servlets - Servlets for OpenID 2.0 Authentication -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Servlet.Security.Servlets; package ASF.Security.Servlets renames Servlet.Security.Servlets;
Package ASF.Security.Servlets moved to Servlet.Security.Servlets
Package ASF.Security.Servlets moved to Servlet.Security.Servlets
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
4773eaaaaaa6a742db8a990db7a971e35618526d
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with ASF.Helpers.Beans; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Components.Wikis; package AWA.Wikis.Beans is use Ada.Strings.Wide_Wide_Unbounded; type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; end record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Wiki_Links_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Wiki_Links_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record -- The wiki module instance. Module : Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read page counter associated with the wiki page. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.WIKI_PAGE_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The wiki page links. Links : aliased Wiki_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_View_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_View_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the information about the wiki page to display it. overriding procedure Load (Bean : in out Wiki_View_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_View_Bean bean instance. function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Wiki_View_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean, Element_Access => Wiki_View_Bean_Access); type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Module : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki space information. overriding procedure Load (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Page Bean -- ------------------------------ -- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from -- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member. -- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the -- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether -- we have to create a new version or not. type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Module : Modules.Wiki_Module_Access := null; -- The page content. Content : Models.Wiki_Content_Ref; Has_Content : Boolean := False; New_Content : Ada.Strings.Unbounded.Unbounded_String; New_Comment : Ada.Strings.Unbounded.Unbounded_String; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Returns True if the wiki page has a new text content and requires -- a new version to be created. function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki page. overriding procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki List Bean -- ------------------------------ -- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record Module : Modules.Wiki_Module_Access := null; Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean; Tags : AWA.Tags.Beans.Entity_Tag_Map; Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access; end record; type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Wiki_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of pages. If a tag was set, filter the list of pages with the tag. procedure Load_List (Into : in out Wiki_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Version List Bean -- ------------------------------ type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record Module : Modules.Wiki_Module_Access := null; Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean; Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access; end record; type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Version_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Version_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Into : in out Wiki_Version_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Post_List_Bean bean instance. function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with ASF.Helpers.Beans; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Components.Wikis; package AWA.Wikis.Beans is use Ada.Strings.Wide_Wide_Unbounded; type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; end record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Wiki_Links_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Wiki_Links_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record -- The wiki module instance. Module : Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read page counter associated with the wiki page. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.WIKI_PAGE_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The wiki page links. Links : aliased Wiki_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_View_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_View_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the information about the wiki page to display it. overriding procedure Load (Bean : in out Wiki_View_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_View_Bean bean instance. function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Wiki_View_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean, Element_Access => Wiki_View_Bean_Access); -- Get a select item list which contains a list of wiki formats. function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Module : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki space information. overriding procedure Load (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Page Bean -- ------------------------------ -- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from -- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member. -- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the -- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether -- we have to create a new version or not. type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Module : Modules.Wiki_Module_Access := null; -- The page content. Content : Models.Wiki_Content_Ref; Has_Content : Boolean := False; New_Content : Ada.Strings.Unbounded.Unbounded_String; New_Comment : Ada.Strings.Unbounded.Unbounded_String; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Returns True if the wiki page has a new text content and requires -- a new version to be created. function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki page. overriding procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki List Bean -- ------------------------------ -- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record Module : Modules.Wiki_Module_Access := null; Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean; Tags : AWA.Tags.Beans.Entity_Tag_Map; Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access; end record; type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Wiki_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of pages. If a tag was set, filter the list of pages with the tag. procedure Load_List (Into : in out Wiki_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Version List Bean -- ------------------------------ type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record Module : Modules.Wiki_Module_Access := null; Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean; Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access; end record; type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Version_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Version_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Into : in out Wiki_Version_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Post_List_Bean bean instance. function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
Declare Create_Format_List_Bean function for the creation of wiki format selector
Declare Create_Format_List_Bean function for the creation of wiki format selector
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1213bc1328d8679dc9b1ba8160597eccebfd5e11
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; -- ------------------------------ -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. -- ------------------------------ procedure Update_Event (Probe : in Probe_Type; Id : in MAT.Events.Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in MAT.Events.Event_Id_Type) is begin Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id); end Update_Event; -- ------------------------------ -- 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.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); Probe.Owner := Into'Unchecked_Access; 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 -- reverse Count .. 1 loop if Count < Frame.Depth then Frame.Frame (Count - I + 1) := 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.Prev_Id := 0; Client.Event.Old_Size := 0; 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; -- Look at the probe definition to gather the target address size. Client.Addr_Size := MAT.Events.T_UINT32; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin if Def.Ref = P_THREAD_SP or Def.Ref = P_FRAME_PC then Client.Addr_Size := Def.Kind; exit; end if; end; 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; -- ------------------------------ -- Get the size of a target address (4 or 8 bytes). -- ------------------------------ function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type is begin return Client.Addr_Size; end Get_Address_Size; 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; -- ------------------------------ -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. -- ------------------------------ procedure Update_Event (Probe : in Probe_Type; Id : in MAT.Events.Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in MAT.Events.Event_Id_Type) is begin Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id); end Update_Event; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; 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.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); Probe.Owner := Into'Unchecked_Access; 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 -- reverse Count .. 1 loop if Count < Frame.Depth then Frame.Frame (Count - I + 1) := 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.Prev_Id := 0; Client.Event.Old_Size := 0; Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); Client.Frames.Insert (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; -- Look at the probe definition to gather the target address size. Client.Addr_Size := MAT.Events.T_UINT32; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin if Def.Ref = P_THREAD_SP or Def.Ref = P_FRAME_PC then Client.Addr_Size := Def.Kind; exit; end if; end; 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; -- ------------------------------ -- Get the size of a target address (4 or 8 bytes). -- ------------------------------ function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type is begin return Client.Addr_Size; end Get_Address_Size; end MAT.Events.Probes;
Update to use the Target_Frames type
Update to use the Target_Frames type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
31788462d0adb9c8b2f197aa945fada9e39f3199
src/security-auth.adb
src/security-auth.adb
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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.Log.Loggers; with Security.Auth.OpenID; with Security.Auth.OAuth.Facebook; with Security.Auth.OAuth.Googleplus; package body Security.Auth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth"); -- ------------------------------ -- Get the provider. -- ------------------------------ function Get_Provider (Assoc : in Association) return String is begin return To_String (Assoc.Provider); end Get_Provider; -- ------------------------------ -- Get the email address -- ------------------------------ function Get_Email (Auth : in Authentication) return String is begin return To_String (Auth.Email); end Get_Email; -- ------------------------------ -- Get the user first name. -- ------------------------------ function Get_First_Name (Auth : in Authentication) return String is begin return To_String (Auth.First_Name); end Get_First_Name; -- ------------------------------ -- Get the user last name. -- ------------------------------ function Get_Last_Name (Auth : in Authentication) return String is begin return To_String (Auth.Last_Name); end Get_Last_Name; -- ------------------------------ -- Get the user full name. -- ------------------------------ function Get_Full_Name (Auth : in Authentication) return String is begin return To_String (Auth.Full_Name); end Get_Full_Name; -- ------------------------------ -- Get the user identity. -- ------------------------------ function Get_Identity (Auth : in Authentication) return String is begin return To_String (Auth.Identity); end Get_Identity; -- ------------------------------ -- Get the user claimed identity. -- ------------------------------ function Get_Claimed_Id (Auth : in Authentication) return String is begin return To_String (Auth.Claimed_Id); end Get_Claimed_Id; -- ------------------------------ -- Get the user language. -- ------------------------------ function Get_Language (Auth : in Authentication) return String is begin return To_String (Auth.Language); end Get_Language; -- ------------------------------ -- Get the user country. -- ------------------------------ function Get_Country (Auth : in Authentication) return String is begin return To_String (Auth.Country); end Get_Country; -- ------------------------------ -- Get the result of the authentication. -- ------------------------------ function Get_Status (Auth : in Authentication) return Auth_Result is begin return Auth.Status; end Get_Status; -- ------------------------------ -- Default principal -- ------------------------------ -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth); end Get_Name; -- ------------------------------ -- Get the user email address. -- ------------------------------ function Get_Email (From : in Principal) return String is begin return Get_Email (From.Auth); end Get_Email; -- ------------------------------ -- Get the authentication data. -- ------------------------------ function Get_Authentication (From : in Principal) return Authentication is begin return From.Auth; end Get_Authentication; -- ------------------------------ -- Create a principal with the given authentication results. -- ------------------------------ function Create_Principal (Auth : in Authentication) return Principal_Access is P : constant Principal_Access := new Principal; begin P.Auth := Auth; return P; end Create_Principal; -- ------------------------------ -- Default factory used by `Initialize`. It supports OpenID, Google, Facebook. -- ------------------------------ function Default_Factory (Provider : in String) return Manager_Access is begin if Provider = PROVIDER_OPENID then return new Security.Auth.OpenID.Manager; elsif Provider = PROVIDER_FACEBOOK then return new Security.Auth.OAuth.Facebook.Manager; elsif Provider = PROVIDER_GOOGLE_PLUS then return new Security.Auth.OAuth.Googleplus.Manager; else Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; end Default_Factory; -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID) is begin Initialize (Realm, Params, Default_Factory'Access, Name); end Initialize; procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Factory : not null access function (Name : in String) return Manager_Access; Name : in String := PROVIDER_OPENID) is Provider : constant String := Params.Get_Parameter ("auth.provider." & Name); Impl : constant Manager_Access := Factory (Provider); begin if Impl = null then Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; Realm.Delegate := Impl; Impl.Initialize (Params, Name); Realm.Provider := To_Unbounded_String (Name); end Initialize; -- ------------------------------ -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) -- ------------------------------ procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is begin if Realm.Delegate /= null then Realm.Delegate.Discover (Name, Result); else -- Result.URL := Realm.Realm; Result.Alias := To_Unbounded_String (""); end if; end Discover; -- ------------------------------ -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) -- ------------------------------ procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association) is begin Result.Provider := Realm.Provider; if Realm.Delegate /= null then Realm.Delegate.Associate (OP, Result); end if; end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is begin if Realm.Delegate /= null then return Realm.Delegate.Get_Authentication_URL (OP, Assoc); else return To_String (OP.URL); end if; end Get_Authentication_URL; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String) is begin if Status /= AUTHENTICATED then Log.Error ("OpenID verification failed: {0}", Message); else Log.Info ("OpenID verification: {0}", Message); end if; Result.Status := Status; end Set_Result; -- ------------------------------ -- Verify the authentication result -- ------------------------------ procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is begin if Realm.Delegate /= null then Realm.Delegate.Verify (Assoc, Request, Result); else Set_Result (Result, SETUP_NEEDED, "Setup is needed"); end if; end Verify; function To_String (OP : End_Point) return String is begin return "openid://" & To_String (OP.URL); end To_String; function To_String (Assoc : Association) return String is begin return "session_type=" & To_String (Assoc.Session_Type) & "&assoc_type=" & To_String (Assoc.Assoc_Type) & "&assoc_handle=" & To_String (Assoc.Assoc_Handle) & "&mac_key=" & To_String (Assoc.Mac_Key); end To_String; end Security.Auth;
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Auth.OpenID; with Security.Auth.OAuth.Facebook; with Security.Auth.OAuth.Googleplus; package body Security.Auth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth"); -- ------------------------------ -- Get the provider. -- ------------------------------ function Get_Provider (Assoc : in Association) return String is begin return To_String (Assoc.Provider); end Get_Provider; -- ------------------------------ -- Get the email address -- ------------------------------ function Get_Email (Auth : in Authentication) return String is begin return To_String (Auth.Email); end Get_Email; -- ------------------------------ -- Get the user first name. -- ------------------------------ function Get_First_Name (Auth : in Authentication) return String is begin return To_String (Auth.First_Name); end Get_First_Name; -- ------------------------------ -- Get the user last name. -- ------------------------------ function Get_Last_Name (Auth : in Authentication) return String is begin return To_String (Auth.Last_Name); end Get_Last_Name; -- ------------------------------ -- Get the user full name. -- ------------------------------ function Get_Full_Name (Auth : in Authentication) return String is begin return To_String (Auth.Full_Name); end Get_Full_Name; -- ------------------------------ -- Get the user identity. -- ------------------------------ function Get_Identity (Auth : in Authentication) return String is begin return To_String (Auth.Identity); end Get_Identity; -- ------------------------------ -- Get the user claimed identity. -- ------------------------------ function Get_Claimed_Id (Auth : in Authentication) return String is begin return To_String (Auth.Claimed_Id); end Get_Claimed_Id; -- ------------------------------ -- Get the user language. -- ------------------------------ function Get_Language (Auth : in Authentication) return String is begin return To_String (Auth.Language); end Get_Language; -- ------------------------------ -- Get the user country. -- ------------------------------ function Get_Country (Auth : in Authentication) return String is begin return To_String (Auth.Country); end Get_Country; -- ------------------------------ -- Get the result of the authentication. -- ------------------------------ function Get_Status (Auth : in Authentication) return Auth_Result is begin return Auth.Status; end Get_Status; -- ------------------------------ -- Default principal -- ------------------------------ -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth); end Get_Name; -- ------------------------------ -- Get the user email address. -- ------------------------------ function Get_Email (From : in Principal) return String is begin return Get_Email (From.Auth); end Get_Email; -- ------------------------------ -- Get the authentication data. -- ------------------------------ function Get_Authentication (From : in Principal) return Authentication is begin return From.Auth; end Get_Authentication; -- ------------------------------ -- Create a principal with the given authentication results. -- ------------------------------ function Create_Principal (Auth : in Authentication) return Principal_Access is P : constant Principal_Access := new Principal; begin P.Auth := Auth; return P; end Create_Principal; -- ------------------------------ -- Default factory used by `Initialize`. It supports OpenID, Google, Facebook. -- ------------------------------ function Default_Factory (Provider : in String) return Manager_Access is begin if Provider = PROVIDER_OPENID then return new Security.Auth.OpenID.Manager; elsif Provider = PROVIDER_FACEBOOK then return new Security.Auth.OAuth.Facebook.Manager; elsif Provider = PROVIDER_GOOGLE_PLUS then return new Security.Auth.OAuth.Googleplus.Manager; else Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; end Default_Factory; -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID) is begin Initialize (Realm, Params, Default_Factory'Access, Name); end Initialize; procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Factory : not null access function (Name : in String) return Manager_Access; Name : in String := PROVIDER_OPENID) is Provider : constant String := Params.Get_Parameter ("auth.provider." & Name); Impl : constant Manager_Access := Factory (Provider); begin if Impl = null then Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; Realm.Delegate := Impl; Impl.Initialize (Params, Name); Realm.Provider := To_Unbounded_String (Name); end Initialize; -- ------------------------------ -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) -- ------------------------------ procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is begin if Realm.Delegate /= null then Realm.Delegate.Discover (Name, Result); else -- Result.URL := Realm.Realm; Result.Alias := To_Unbounded_String (""); end if; end Discover; -- ------------------------------ -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) -- ------------------------------ procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association) is begin Result.Provider := Realm.Provider; if Realm.Delegate /= null then Realm.Delegate.Associate (OP, Result); end if; end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is begin if Realm.Delegate /= null then return Realm.Delegate.Get_Authentication_URL (OP, Assoc); else return To_String (OP.URL); end if; end Get_Authentication_URL; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String) is begin if Status /= AUTHENTICATED then Log.Error ("OpenID verification failed: {0}", Message); else Log.Info ("OpenID verification: {0}", Message); end if; Result.Status := Status; end Set_Result; -- ------------------------------ -- Verify the authentication result -- ------------------------------ procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is begin if Realm.Delegate /= null then Realm.Delegate.Verify (Assoc, Request, Result); else Set_Result (Result, SETUP_NEEDED, "Setup is needed"); end if; end Verify; function To_String (OP : End_Point) return String is begin return "openid://" & To_String (OP.URL); end To_String; function To_String (Assoc : Association) return String is begin return "session_type=" & To_String (Assoc.Session_Type) & "&assoc_type=" & To_String (Assoc.Assoc_Type) & "&assoc_handle=" & To_String (Assoc.Assoc_Handle) & "&mac_key=" & To_String (Assoc.Mac_Key); end To_String; overriding procedure Finalize (Realm : in out Manager) is procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Manager_Access); begin Free (Realm.Delegate); end Finalize; end Security.Auth;
Add Finalize and release the OAuth delegate implementation
Add Finalize and release the OAuth delegate implementation
Ada
apache-2.0
stcarrez/ada-security
7c94effc07efc4381726941bd3a4579b7fef06e5
src/util-commands.adb
src/util-commands.adb
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Ada.Characters.Handling; package body Util.Commands is -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in Default_Argument_List) return Natural is Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count > List.Offset then return Count - List.Offset; else return 0; end if; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String is begin return Ada.Command_Line.Argument (Pos + List.Offset); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Default_Argument_List) return String is pragma Unreferenced (List); begin return Ada.Command_Line.Command_Name; end Get_Command_Name; -- ------------------------------ -- Set the argument list to the given string and split the arguments. -- ------------------------------ procedure Initialize (List : in out String_Argument_List; Line : in String) is First : Natural := Line'First; begin List.Length := Line'Length; List.Line (1 .. Line'Length) := Line; List.Count := 0; loop while First <= Line'Length and then Ada.Characters.Handling.Is_Space (List.Line (First)) loop First := First + 1; end loop; exit when First > Line'Length; List.Start_Pos (List.Count) := First; while First <= Line'Length and then not Ada.Characters.Handling.Is_Space (List.Line (First)) loop First := First + 1; end loop; List.End_Pos (List.Count) := First - 1; List.Count := List.Count + 1; end loop; if List.Count > 0 then List.Count := List.Count - 1; end if; end Initialize; -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in String_Argument_List) return Natural is begin return List.Count; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String is begin return List.Line (List.Start_Pos (Pos) .. List.End_Pos (Pos)); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ overriding function Get_Command_Name (List : in String_Argument_List) return String is begin return List.Line (List.Start_Pos (0) .. List.End_Pos (0)); end Get_Command_Name; -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ function Get_Count (List : in Dynamic_Argument_List) return Natural is begin return Natural (List.List.Length); end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ function Get_Argument (List : in Dynamic_Argument_List; Pos : in Positive) return String is begin return List.List.Element (Pos); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Dynamic_Argument_List) return String is begin return List.List.Element (1); end Get_Command_Name; end Util.Commands;
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Ada.Characters.Handling; package body Util.Commands is -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in Default_Argument_List) return Natural is Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count > List.Offset then return Count - List.Offset; else return 0; end if; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String is begin return Ada.Command_Line.Argument (Pos + List.Offset); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Default_Argument_List) return String is pragma Unreferenced (List); begin return Ada.Command_Line.Command_Name; end Get_Command_Name; -- ------------------------------ -- Set the argument list to the given string and split the arguments. -- ------------------------------ procedure Initialize (List : in out String_Argument_List; Line : in String) is First : Natural := Line'First; begin List.Length := Line'Length; List.Line (1 .. Line'Length) := Line; List.Count := 0; loop while First <= Line'Length and then Ada.Characters.Handling.Is_Space (List.Line (First)) loop First := First + 1; end loop; exit when First > Line'Length; List.Start_Pos (List.Count) := First; while First <= Line'Length and then not Ada.Characters.Handling.Is_Space (List.Line (First)) loop First := First + 1; end loop; List.End_Pos (List.Count) := First - 1; List.Count := List.Count + 1; end loop; if List.Count > 0 then List.Count := List.Count - 1; end if; end Initialize; -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in String_Argument_List) return Natural is begin return List.Count; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String is begin return List.Line (List.Start_Pos (Pos) .. List.End_Pos (Pos)); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ overriding function Get_Command_Name (List : in String_Argument_List) return String is begin return List.Line (List.Start_Pos (0) .. List.End_Pos (0)); end Get_Command_Name; -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ function Get_Count (List : in Dynamic_Argument_List) return Natural is begin return Natural (List.List.Length); end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ function Get_Argument (List : in Dynamic_Argument_List; Pos : in Positive) return String is begin return List.List.Element (Pos); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Dynamic_Argument_List) return String is begin return Ada.Strings.Unbounded.To_String (List.Name); end Get_Command_Name; end Util.Commands;
Update Get_Command_Name to use the name member
Update Get_Command_Name to use the name member
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
07d5285a4c5625970db92b5d6ae0b0e89701f464
mat/src/mat-consoles.adb
mat/src/mat-consoles.adb
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; end MAT.Consoles;
Implement the Print_Size operation
Implement the Print_Size operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
31f0a951048a64f8f64aa47ec156f585b144ab66
regtests/ado-drivers-tests.adb
regtests/ado-drivers-tests.adb
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with Regtests; with ADO.Statements; with ADO.Sessions; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Port", Test_Set_Connection_Port'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Database", Test_Set_Connection_Database'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Databases (DB Closed errors)", Test_Closed_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("sqlite"); Postgres_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("postgresql"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null or Postgres_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("sqlite"); Postgres_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("postgresql"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Postgres_Driver /= null then T.Assert (Postgres_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; if Mysql_Driver /= null and Postgres_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Postgres_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; if Sqlite_Driver /= null and Postgres_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index /= Postgres_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); exception when E : ADO.Drivers.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the Set_Port operation. -- ------------------------------ procedure Test_Set_Connection_Port (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Port (1234); Util.Tests.Assert_Equals (T, 1234, Controller.Get_Port, "Configuration Set_Port returned invalid value"); exception when E : ADO.Drivers.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Port; -- ------------------------------ -- Test the Set_Database operation. -- ------------------------------ procedure Test_Set_Connection_Database (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Database ("test-database"); Util.Tests.Assert_Equals (T, "test-database", Controller.Get_Database, "Configuration Set_Database returned invalid value"); exception when E : ADO.Drivers.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Database; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use type ADO.Sessions.Connection_Status; C : ADO.Sessions.Session; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (C.Get_Status = ADO.Sessions.CLOSED, "The database connection must be closed for an empty connection"); -- Create_Statement must raise Session_Error. begin Stmt := C.Create_Statement (""); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.Session_Error => null; end; -- Create_Statement must raise Session_Error. begin Stmt := C.Create_Statement ("select"); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.Session_Error => null; end; end Test_Empty_Connection; -- ------------------------------ -- Test the connection operations on a closed connection. -- ------------------------------ procedure Test_Closed_Connection (T : in out Test) is begin declare DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; DB2 : ADO.Sessions.Master_Session := DB; Stmt : ADO.Statements.Query_Statement; begin DB.Close; Stmt := DB2.Create_Statement ("SELECT name FROM test_table"); Stmt.Execute; Util.Tests.Fail (T, "No Session_Error exception was raised"); exception when ADO.Sessions.Session_Error => null; end; declare DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; DB2 : ADO.Sessions.Master_Session := DB; begin DB.Close; DB2.Begin_Transaction; Util.Tests.Fail (T, "No Session_Error exception was raised"); exception when ADO.Sessions.Session_Error => null; end; declare DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; DB2 : ADO.Sessions.Master_Session := DB; begin DB.Close; DB2.Commit; Util.Tests.Fail (T, "No Session_Error exception was raised"); exception when ADO.Sessions.Session_Error => null; end; declare DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; DB2 : ADO.Sessions.Master_Session := DB; begin DB.Close; DB2.Rollback; Util.Tests.Fail (T, "No Session_Error exception was raised"); exception when ADO.Sessions.Session_Error => null; end; end Test_Closed_Connection; end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with Regtests; with ADO.Configs; with ADO.Statements; with ADO.Sessions; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Configs; use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Port", Test_Set_Connection_Port'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Database", Test_Set_Connection_Database'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Databases (DB Closed errors)", Test_Closed_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("sqlite"); Postgres_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("postgresql"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null or Postgres_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("sqlite"); Postgres_Driver : constant Driver_Access := Drivers.Connections.Get_Driver ("postgresql"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Postgres_Driver /= null then T.Assert (Postgres_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; if Mysql_Driver /= null and Postgres_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Postgres_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; if Sqlite_Driver /= null and Postgres_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index /= Postgres_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); exception when E : ADO.Configs.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the Set_Port operation. -- ------------------------------ procedure Test_Set_Connection_Port (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Port (1234); Util.Tests.Assert_Equals (T, 1234, Controller.Get_Port, "Configuration Set_Port returned invalid value"); exception when E : ADO.Configs.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Port; -- ------------------------------ -- Test the Set_Database operation. -- ------------------------------ procedure Test_Set_Connection_Database (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Database ("test-database"); Util.Tests.Assert_Equals (T, "test-database", Controller.Get_Database, "Configuration Set_Database returned invalid value"); exception when E : ADO.Configs.Connection_Error => Util.Tests.Assert_Equals (T, "Driver 'mysql' not found", Ada.Exceptions.Exception_Message (E), "Invalid exception message"); end Test_Set_Connection_Database; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use type ADO.Sessions.Connection_Status; C : ADO.Sessions.Session; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (C.Get_Status = ADO.Sessions.CLOSED, "The database connection must be closed for an empty connection"); -- Create_Statement must raise Session_Error. begin Stmt := C.Create_Statement (""); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.Session_Error => null; end; -- Create_Statement must raise Session_Error. begin Stmt := C.Create_Statement ("select"); T.Fail ("No exception raised for Create_Statement"); exception when ADO.Sessions.Session_Error => null; end; end Test_Empty_Connection; -- ------------------------------ -- Test the connection operations on a closed connection. -- ------------------------------ procedure Test_Closed_Connection (T : in out Test) is begin declare DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; DB2 : constant ADO.Sessions.Master_Session := DB; Stmt : ADO.Statements.Query_Statement; begin DB.Close; Stmt := DB2.Create_Statement ("SELECT name FROM test_table"); Stmt.Execute; Util.Tests.Fail (T, "No Session_Error exception was raised"); exception when ADO.Sessions.Session_Error => null; end; declare DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; DB2 : ADO.Sessions.Master_Session := DB; begin DB.Close; DB2.Begin_Transaction; Util.Tests.Fail (T, "No Session_Error exception was raised"); exception when ADO.Sessions.Session_Error => null; end; declare DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; DB2 : ADO.Sessions.Master_Session := DB; begin DB.Close; DB2.Commit; Util.Tests.Fail (T, "No Session_Error exception was raised"); exception when ADO.Sessions.Session_Error => null; end; declare DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; DB2 : ADO.Sessions.Master_Session := DB; begin DB.Close; DB2.Rollback; Util.Tests.Fail (T, "No Session_Error exception was raised"); exception when ADO.Sessions.Session_Error => null; end; end Test_Closed_Connection; end ADO.Drivers.Tests;
Update after refactoring of ADO.Drivers.Connections
Update after refactoring of ADO.Drivers.Connections
Ada
apache-2.0
stcarrez/ada-ado
428347baee805460276a3ff664af1c8ac6b136d4
src/dynamo.adb
src/dynamo.adb
----------------------------------------------------------------------- -- dynamo -- Ada Code Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Sax.Readers; use Sax.Readers; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada.Command_Line; with Util.Log.Loggers; with Gen.Generator; procedure DBMapper is use Ada; use Ada.Strings.Unbounded; use Ada.Command_Line; Release : constant String := "Dynamo Ada Generator 0.3, Stephane Carrez"; Copyright : constant String := "Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc."; ----------------- -- Output_File -- ----------------- -------------------------------------------------- -- Usage -------------------------------------------------- procedure Usage is use Ada.Text_IO; begin Put_Line (Release); Put_Line (Copyright); New_Line; Put ("Usage: "); Put (Command_Name); Put_Line (" [-v] [-o directory] [-t templates] model.xml"); Put_Line ("where:"); Put_Line (" -v Verbose"); Put_Line (" -q Query mode"); Put_Line (" -o directory Directory where the Ada mapping files are generated"); Put_Line (" -t templates Directory where the Ada templates are defined"); Put_Line (" -c dir Directory where the Ada templates and configurations are defined"); New_Line; Put_Line (" -h Requests this info."); New_Line; end Usage; File_Count : Natural := 0; Out_Dir : Unbounded_String; Config_Dir : Unbounded_String; Template_Dir : Unbounded_String; begin -- Parse the command line loop case Getopt ("o: t: c:") is when ASCII.Nul => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 't' => Template_Dir := To_Unbounded_String (Parameter & "/"); when 'c' => Config_Dir := To_Unbounded_String (Parameter & "/"); when others => null; end case; end loop; if Length (Config_Dir) = 0 then Config_Dir := To_Unbounded_String ("config/"); end if; -- Configure the logs Util.Log.Loggers.Initialize (To_String (Config_Dir) & "log4j.properties"); declare Generator : Gen.Generator.Handler; begin if Length (Out_Dir) > 0 then Gen.Generator.Set_Result_Directory (Generator, Out_Dir); end if; if Length (Template_Dir) > 0 then Gen.Generator.Set_Template_Directory (Generator, Template_Dir); end if; Gen.Generator.Initialize (Generator, Config_Dir); -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; Gen.Generator.Read_Model (Generator, Model_File); end; end loop; if File_Count = 0 then Usage; Set_Exit_Status (2); return; end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); -- Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_PACKAGE, "model"); -- Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_TABLE, "sql"); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when E : XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); end DBMapper;
----------------------------------------------------------------------- -- dynamo -- Ada Code Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Sax.Readers; use Sax.Readers; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada.Command_Line; with Util.Log.Loggers; with Gen.Generator; procedure Dynamo is use Ada; use Ada.Strings.Unbounded; use Ada.Command_Line; Release : constant String := "Dynamo Ada Generator 0.3, Stephane Carrez"; Copyright : constant String := "Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc."; ----------------- -- Output_File -- ----------------- -------------------------------------------------- -- Usage -------------------------------------------------- procedure Usage is use Ada.Text_IO; begin Put_Line (Release); Put_Line (Copyright); New_Line; Put ("Usage: "); Put (Command_Name); Put_Line (" [-v] [-o directory] [-t templates] model.xml"); Put_Line ("where:"); Put_Line (" -v Verbose"); Put_Line (" -q Query mode"); Put_Line (" -o directory Directory where the Ada mapping files are generated"); Put_Line (" -t templates Directory where the Ada templates are defined"); Put_Line (" -c dir Directory where the Ada templates and configurations are defined"); New_Line; Put_Line (" -h Requests this info."); New_Line; end Usage; File_Count : Natural := 0; Out_Dir : Unbounded_String; Config_Dir : Unbounded_String; Template_Dir : Unbounded_String; begin -- Parse the command line loop case Getopt ("o: t: c:") is when ASCII.Nul => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 't' => Template_Dir := To_Unbounded_String (Parameter & "/"); when 'c' => Config_Dir := To_Unbounded_String (Parameter & "/"); when others => null; end case; end loop; if Length (Config_Dir) = 0 then Config_Dir := To_Unbounded_String ("config/"); end if; -- Configure the logs Util.Log.Loggers.Initialize (To_String (Config_Dir) & "log4j.properties"); declare Generator : Gen.Generator.Handler; begin if Length (Out_Dir) > 0 then Gen.Generator.Set_Result_Directory (Generator, Out_Dir); end if; if Length (Template_Dir) > 0 then Gen.Generator.Set_Template_Directory (Generator, Template_Dir); end if; Gen.Generator.Initialize (Generator, Config_Dir); -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; Gen.Generator.Read_Model (Generator, Model_File); end; end loop; if File_Count = 0 then Usage; Set_Exit_Status (2); return; end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); -- Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_PACKAGE, "model"); -- Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_TABLE, "sql"); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when E : XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); end Dynamo;
Rename procedure
Rename procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0705081413d61f06e3cd935da098e00390f7bc2a
awa/src/awa-events-queues-persistents.adb
awa/src/awa-events-queues-persistents.adb
----------------------------------------------------------------------- -- awa-events-queues-persistents -- AWA Event Queues -- Copyright (C) 2012, 2013, 2014, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with Util.Serialize.Tools; with AWA.Services.Contexts; with AWA.Applications; with AWA.Events.Services; with AWA.Users.Models; with ADO; with ADO.Sessions; with ADO.SQL; package body AWA.Events.Queues.Persistents is package ASC renames AWA.Services.Contexts; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents"); -- ------------------------------ -- Get the queue name. -- ------------------------------ overriding function Get_Name (From : in Persistent_Queue) return String is begin return From.Name; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ overriding function Get_Queue (From : in Persistent_Queue) return Models.Queue_Ref is begin return From.Queue; end Get_Queue; -- ------------------------------ -- Queue the event. The event is saved in the database with a relation to -- the user, the user session, the event queue and the event type. -- ------------------------------ overriding procedure Enqueue (Into : in out Persistent_Queue; Event : in AWA.Events.Module_Event'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant ASC.Service_Context_Access := ASC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Event.Get_Event_Kind); end Set_Event; begin App.Do_Event_Manager (Set_Event'Access); Ctx.Start; Msg.Set_Queue (Into.Queue); Msg.Set_User (Ctx.Get_User); Msg.Set_Session (Ctx.Get_User_Session); Msg.Set_Create_Date (Event.Get_Time); Msg.Set_Status (AWA.Events.Models.QUEUED); Msg.Set_Entity_Id (Event.Get_Entity_Identifier); Msg.Set_Entity_Type (Event.Entity_Type); -- Collect the event parameters in a string and format the result in JSON. Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props)); Msg.Save (DB); Ctx.Commit; Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id)); end Enqueue; overriding procedure Dequeue (From : in out Persistent_Queue; Process : access procedure (Event : in Module_Event'Class)) is -- Prepare the message by indicating in the database it is going -- to be processed by the given server and task. procedure Prepare_Message (Msg : in out Models.Message_Ref); -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref); -- Finish processing the message by marking it as being processed. procedure Finish_Message (Msg : in out Models.Message_Ref); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Messages : Models.Message_Vector; Query : ADO.SQL.Query; Task_Id : constant Integer := 0; procedure Prepare_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSING); Msg.Set_Server_Id (From.Server_Id); Msg.Set_Task_Id (Task_Id); Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Prepare_Message; procedure Dispatch_Message (Msg : in out Models.Message_Ref) is User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User; Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session; Name : constant String := Msg.Get_Message_Type.Get_Name; Event : Module_Event; procedure Action; procedure Action is begin Process (Event); end Action; procedure Run is new AWA.Services.Contexts.Run_As (Action); begin Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Name)); Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props); Event.Set_Entity_Identifier (Msg.Get_Entity_Id); Event.Entity_Type := Msg.Get_Entity_Type; if not User.Is_Null then Log.Info ("Dispatching event {0} for user{1} session{2}", Name, ADO.Identifier'Image (User.Get_Id), ADO.Identifier'Image (Session.Get_Id)); else Log.Info ("Dispatching event {0}", Name); end if; -- Run the Process action on behalf of the user associated -- with the message. Run (AWA.Users.Models.User_Ref (User), AWA.Users.Models.Session_Ref (Session)); exception when E : others => Log.Error ("Exception when processing event " & Name, E, True); end Dispatch_Message; -- ------------------------------ -- Finish processing the message by marking it as being processed. -- ------------------------------ procedure Finish_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSED); Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Finish_Message; Count : Natural; begin Ctx.Start; Query.Set_Filter ("o.status = 0 AND o.queue_id = :queue " & "ORDER BY o.priority DESC, " & "o.id ASC LIMIT :max"); Query.Bind_Param ("queue", From.Queue.Get_Id); Query.Bind_Param ("max", From.Max_Batch); Models.List (Messages, DB, Query); Count := Natural (Messages.Length); -- Prepare the event messages by marking them in the database. -- This makes sure that no other server or task (if any), will process them. if Count > 0 then for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Prepare_Message'Access); end loop; end if; Ctx.Commit; if Count = 0 then return; end if; Log.Info ("Dispatching {0} events", Natural'Image (Count)); -- Dispatch each event. for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Dispatch_Message'Access); end loop; -- After having dispatched the events, mark them as dispatched in the queue. Ctx.Start; for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Finish_Message'Access); end loop; Ctx.Commit; end Dequeue; -- ------------------------------ -- Create the queue associated with the given name and configure it by using -- the configuration properties. -- ------------------------------ function Create_Queue (Name : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Access is pragma Unreferenced (Props, Context); Ctx : constant ASC.Service_Context_Access := ASC.Current; Session : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Queue : AWA.Events.Models.Queue_Ref; Query : ADO.SQL.Query; Found : Boolean; begin Session.Begin_Transaction; -- Find the queue instance which matches the name. Query.Set_Filter ("o.name = ?"); Query.Add_Param (Name); Queue.Find (Session => Session, Query => Query, Found => Found); -- But create the queue instance if it does not exist. if not Found then Log.Info ("Creating database queue {0}", Name); Queue.Set_Name (Name); Queue.Save (Session); else Log.Info ("Using database queue {0}", Name); end if; Session.Commit; return new Persistent_Queue '(Name_Length => Name'Length, Name => Name, Queue => Queue, others => <>); end Create_Queue; end AWA.Events.Queues.Persistents;
----------------------------------------------------------------------- -- awa-events-queues-persistents -- AWA Event Queues -- Copyright (C) 2012, 2013, 2014, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with Util.Serialize.Tools; with AWA.Services.Contexts; with AWA.Applications; with AWA.Events.Services; with AWA.Users.Models; with ADO; with ADO.Sessions; with ADO.SQL; package body AWA.Events.Queues.Persistents is package ASC renames AWA.Services.Contexts; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents"); -- ------------------------------ -- Get the queue name. -- ------------------------------ overriding function Get_Name (From : in Persistent_Queue) return String is begin return From.Name; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ overriding function Get_Queue (From : in Persistent_Queue) return Models.Queue_Ref is begin return From.Queue; end Get_Queue; -- ------------------------------ -- Queue the event. The event is saved in the database with a relation to -- the user, the user session, the event queue and the event type. -- ------------------------------ overriding procedure Enqueue (Into : in out Persistent_Queue; Event : in AWA.Events.Module_Event'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant ASC.Service_Context_Access := ASC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Event.Get_Event_Kind); end Set_Event; begin App.Do_Event_Manager (Set_Event'Access); Ctx.Start; Msg.Set_Queue (Into.Queue); Msg.Set_User (Ctx.Get_User); Msg.Set_Session (Ctx.Get_User_Session); Msg.Set_Create_Date (Event.Get_Time); Msg.Set_Status (AWA.Events.Models.QUEUED); Msg.Set_Entity_Id (Event.Get_Entity_Identifier); Msg.Set_Entity_Type (Event.Entity_Type); -- Collect the event parameters in a string and format the result in JSON. Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props)); Msg.Save (DB); Ctx.Commit; Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id)); end Enqueue; overriding procedure Dequeue (From : in out Persistent_Queue; Process : access procedure (Event : in Module_Event'Class)) is -- Prepare the message by indicating in the database it is going -- to be processed by the given server and task. procedure Prepare_Message (Msg : in out Models.Message_Ref); -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref); -- Finish processing the message by marking it as being processed. procedure Finish_Message (Msg : in out Models.Message_Ref); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Messages : Models.Message_Vector; Query : ADO.SQL.Query; Task_Id : constant Integer := 0; procedure Prepare_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSING); Msg.Set_Server_Id (From.Server_Id); Msg.Set_Task_Id (Task_Id); Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Prepare_Message; procedure Dispatch_Message (Msg : in out Models.Message_Ref) is User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User; Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session; Name : constant String := Msg.Get_Message_Type.Get_Name; Event : Module_Event; procedure Action; procedure Action is begin Process (Event); end Action; procedure Run is new AWA.Services.Contexts.Run_As (Action); begin Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Name)); Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props); Event.Set_Entity_Identifier (Msg.Get_Entity_Id); Event.Entity_Type := Msg.Get_Entity_Type; if not User.Is_Null then Log.Info ("Dispatching event {0} for user{1} session{2}", Name, ADO.Identifier'Image (User.Get_Id), ADO.Identifier'Image (Session.Get_Id)); else Log.Info ("Dispatching event {0}", Name); end if; -- Run the Process action on behalf of the user associated -- with the message. Run (AWA.Users.Models.User_Ref (User), AWA.Users.Models.Session_Ref (Session)); exception when E : others => Log.Error ("Exception when processing event " & Name, E, True); end Dispatch_Message; -- ------------------------------ -- Finish processing the message by marking it as being processed. -- ------------------------------ procedure Finish_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSED); Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Finish_Message; Count : Natural; begin Ctx.Start; Query.Set_Filter ("o.status = 0 AND o.queue_id = :queue " & "ORDER BY o.priority DESC, " & "o.id ASC LIMIT :max"); Query.Bind_Param ("queue", From.Queue.Get_Id); Query.Bind_Param ("max", From.Max_Batch); Models.List (Messages, DB, Query); Count := Natural (Messages.Length); -- Prepare the event messages by marking them in the database. -- This makes sure that no other server or task (if any), will process them. if Count > 0 then for I in 1 .. Count loop Messages.Update_Element (Index => I, Process => Prepare_Message'Access); end loop; end if; Ctx.Commit; if Count = 0 then return; end if; Log.Info ("Dispatching {0} events", Natural'Image (Count)); -- Dispatch each event. for I in 1 .. Count loop Messages.Update_Element (Index => I, Process => Dispatch_Message'Access); end loop; -- After having dispatched the events, mark them as dispatched in the queue. Ctx.Start; for I in 1 .. Count loop Messages.Update_Element (Index => I, Process => Finish_Message'Access); end loop; Ctx.Commit; end Dequeue; -- ------------------------------ -- Create the queue associated with the given name and configure it by using -- the configuration properties. -- ------------------------------ function Create_Queue (Name : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Access is pragma Unreferenced (Props, Context); Ctx : constant ASC.Service_Context_Access := ASC.Current; Session : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Queue : AWA.Events.Models.Queue_Ref; Query : ADO.SQL.Query; Found : Boolean; begin Session.Begin_Transaction; -- Find the queue instance which matches the name. Query.Set_Filter ("o.name = ?"); Query.Add_Param (Name); Queue.Find (Session => Session, Query => Query, Found => Found); -- But create the queue instance if it does not exist. if not Found then Log.Info ("Creating database queue {0}", Name); Queue.Set_Name (Name); Queue.Save (Session); else Log.Info ("Using database queue {0}", Name); end if; Session.Commit; return new Persistent_Queue '(Name_Length => Name'Length, Name => Name, Queue => Queue, others => <>); end Create_Queue; end AWA.Events.Queues.Persistents;
Update to use Positive index for the event list
Update to use Positive index for the event list
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8f2d71bc80da422ace305347118d2e608a4a7a4b
src/sqlite/ado-drivers-connections-sqlite.ads
src/sqlite/ado-drivers-connections-sqlite.ads
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- 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); end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; private with Ada.Containers.Doubly_Linked_Lists; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; URI : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); package Database_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Ref.Ref, "=" => ADO.Drivers.Connections.Ref."="); protected type Sqlite_Connections is procedure Open (Config : in Configuration'Class; Result : in out Ref.Ref'Class); private List : Database_List.List; end Sqlite_Connections; type Sqlite_Driver is new ADO.Drivers.Connections.Driver with record Map : Sqlite_Connections; end record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- 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); -- Deletes the SQLite driver. overriding procedure Finalize (D : in out Sqlite_Driver); end ADO.Drivers.Connections.Sqlite;
Declare Sqlite_Connections protected type for the management of databse connections
Declare Sqlite_Connections protected type for the management of databse connections
Ada
apache-2.0
stcarrez/ada-ado
f81ff2e98179ebdcc1bcbcbe45eecfc39bb6185f
awa/src/awa-commands-start.adb
awa/src/awa-commands-start.adb
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Servlet.Core; with Servlet.Server; with GNAT.Sockets; with AWA.Applications; package body AWA.Commands.Start is use Ada.Strings.Unbounded; use GNAT.Sockets; use type System.Address; -- ------------------------------ -- Start the server and all the application that have been registered. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Configure (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access); procedure Shutdown (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; procedure Configure (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access) is begin if Application.all in AWA.Applications.Application'Class then Configure (AWA.Applications.Application'Class (Application.all), URI (URI'First + 1 .. URI'Last), Context); Count := Count + 1; end if; end Configure; procedure Shutdown (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access) is begin if Application.all in AWA.Applications.Application'Class then AWA.Applications.Application'Class (Application.all).Close; end if; end Shutdown; Config : Servlet.Server.Configuration; Address : GNAT.Sockets.Sock_Addr_Type; Listen : GNAT.Sockets.Socket_Type; Socket : GNAT.Sockets.Socket_Type; begin -- If daemon(3) is available and -d is defined, run it so that the parent -- process terminates and the child process continues. if Command.Daemon and Sys_Daemon'Address /= System.Null_Address then declare Result : constant Integer := Sys_Daemon (1, 0); begin if Result /= 0 then Context.Console.Error ("Cannot run in background"); end if; end; end if; Config.Listening_Port := Command.Listening_Port; Config.Max_Connection := Command.Max_Connection; Config.TCP_No_Delay := Command.TCP_No_Delay; if Command.Upload'Length > 0 then Config.Upload_Directory := To_Unbounded_String (Command.Upload.all); end if; Command_Drivers.WS.Configure (Config); Command_Drivers.WS.Iterate (Configure'Access); if Count = 0 then Context.Console.Error (-("There is no application")); return; end if; Context.Console.Notice (N_INFO, "Starting..."); Command_Drivers.WS.Start; GNAT.Sockets.Create_Socket (Listen); Address.Addr := GNAT.Sockets.Loopback_Inet_Addr; if Command.Management_Port > 0 then Address.Port := Port_Type (Command.Management_Port); else Address.Port := 0; end if; GNAT.Sockets.Bind_Socket (Listen, Address); GNAT.Sockets.Listen_Socket (Listen); loop GNAT.Sockets.Accept_Socket (Listen, Socket, Address); exit; end loop; GNAT.Sockets.Close_Socket (Socket); GNAT.Sockets.Close_Socket (Listen); Command_Drivers.WS.Iterate (Shutdown'Access); end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); GC.Define_Switch (Config => Config, Output => Command.Management_Port'Access, Switch => "-m:", Long_Switch => "--management-port=", Initial => Command.Management_Port, Argument => "NUMBER", Help => -("The server listening management port on localhost")); GC.Define_Switch (Config => Config, Output => Command.Listening_Port'Access, Switch => "-p:", Long_Switch => "--port=", Initial => Command.Listening_Port, Argument => "NUMBER", Help => -("The server listening port")); GC.Define_Switch (Config => Config, Output => Command.Max_Connection'Access, Switch => "-C:", Long_Switch => "--connection=", Initial => Command.Max_Connection, Argument => "NUMBER", Help => -("The number of connections handled")); GC.Define_Switch (Config => Config, Output => Command.Upload'Access, Switch => "-u:", Long_Switch => "--upload=", Argument => "PATH", Help => -("The server upload directory")); GC.Define_Switch (Config => Config, Output => Command.TCP_No_Delay'Access, Switch => "-n", Long_Switch => "--tcp-no-delay", Help => -("Enable the TCP no delay option")); if Sys_Daemon'Address /= System.Null_Address then GC.Define_Switch (Config => Config, Output => Command.Daemon'Access, Switch => "-d", Long_Switch => "--daemon", Help => -("Run the server in the background")); end if; AWA.Commands.Setup (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; begin Command_Drivers.Driver.Add_Command ("start", -("start the web server"), Command'Access); end AWA.Commands.Start;
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Servlet.Core; with Servlet.Server; with GNAT.Sockets; with AWA.Applications; package body AWA.Commands.Start is use Ada.Strings.Unbounded; use GNAT.Sockets; use type System.Address; -- ------------------------------ -- Start the server and all the application that have been registered. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Start_Server (Context); Command.Wait_Server (Context); end Execute; -- ------------------------------ -- Start the server and all the application that have been registered. -- ------------------------------ procedure Start_Server (Command : in out Command_Type; Context : in out Context_Type) is procedure Configure (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; procedure Configure (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access) is begin if Application.all in AWA.Applications.Application'Class then Configure (AWA.Applications.Application'Class (Application.all), URI (URI'First + 1 .. URI'Last), Context); Count := Count + 1; end if; end Configure; Config : Servlet.Server.Configuration; begin -- If daemon(3) is available and -d is defined, run it so that the parent -- process terminates and the child process continues. if Command.Daemon and Sys_Daemon'Address /= System.Null_Address then declare Result : constant Integer := Sys_Daemon (1, 0); begin if Result /= 0 then Context.Console.Error ("Cannot run in background"); end if; end; end if; Config.Listening_Port := Command.Listening_Port; Config.Max_Connection := Command.Max_Connection; Config.TCP_No_Delay := Command.TCP_No_Delay; if Command.Upload'Length > 0 then Config.Upload_Directory := To_Unbounded_String (Command.Upload.all); end if; Command_Drivers.WS.Configure (Config); Command_Drivers.WS.Iterate (Configure'Access); if Count = 0 then Context.Console.Error (-("There is no application")); return; end if; Context.Console.Notice (N_INFO, "Starting..."); Command_Drivers.WS.Start; end Start_Server; -- ------------------------------ -- Wait for the server to shutdown. -- ------------------------------ procedure Wait_Server (Command : in out Command_Type; Context : in out Context_Type) is procedure Shutdown (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access); procedure Shutdown (URI : in String; Application : in Servlet.Core.Servlet_Registry_Access) is begin if Application.all in AWA.Applications.Application'Class then AWA.Applications.Application'Class (Application.all).Close; end if; end Shutdown; Address : GNAT.Sockets.Sock_Addr_Type; Listen : GNAT.Sockets.Socket_Type; Socket : GNAT.Sockets.Socket_Type; begin GNAT.Sockets.Create_Socket (Listen); Address.Addr := GNAT.Sockets.Loopback_Inet_Addr; if Command.Management_Port > 0 then Address.Port := Port_Type (Command.Management_Port); else Address.Port := 0; end if; GNAT.Sockets.Bind_Socket (Listen, Address); GNAT.Sockets.Listen_Socket (Listen); loop GNAT.Sockets.Accept_Socket (Listen, Socket, Address); exit; end loop; GNAT.Sockets.Close_Socket (Socket); GNAT.Sockets.Close_Socket (Listen); Command_Drivers.WS.Iterate (Shutdown'Access); end Wait_Server; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); GC.Define_Switch (Config => Config, Output => Command.Management_Port'Access, Switch => "-m:", Long_Switch => "--management-port=", Initial => Command.Management_Port, Argument => "NUMBER", Help => -("The server listening management port on localhost")); GC.Define_Switch (Config => Config, Output => Command.Listening_Port'Access, Switch => "-p:", Long_Switch => "--port=", Initial => Command.Listening_Port, Argument => "NUMBER", Help => -("The server listening port")); GC.Define_Switch (Config => Config, Output => Command.Max_Connection'Access, Switch => "-C:", Long_Switch => "--connection=", Initial => Command.Max_Connection, Argument => "NUMBER", Help => -("The number of connections handled")); GC.Define_Switch (Config => Config, Output => Command.Upload'Access, Switch => "-u:", Long_Switch => "--upload=", Argument => "PATH", Help => -("The server upload directory")); GC.Define_Switch (Config => Config, Output => Command.TCP_No_Delay'Access, Switch => "-n", Long_Switch => "--tcp-no-delay", Help => -("Enable the TCP no delay option")); if Sys_Daemon'Address /= System.Null_Address then GC.Define_Switch (Config => Config, Output => Command.Daemon'Access, Switch => "-d", Long_Switch => "--daemon", Help => -("Run the server in the background")); end if; AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; begin Command_Drivers.Driver.Add_Command ("start", -("start the web server"), Command'Access); end AWA.Commands.Start;
Split the Execute into a Start_Server and Wait_Server operation
Split the Execute into a Start_Server and Wait_Server operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
75b106ba4a67be115e5d04d120084d2fb0dc29c2
awa/src/awa-events.ads
awa/src/awa-events.ads
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Applications; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; -- ------------------------------ -- Event kind definition -- ------------------------------ -- This package must be instantiated for each event that a module can post. generic Name : String; package Definition is function Kind return Event_Index; pragma Inline_Always (Kind); end Definition; -- Exception raised if an event name is not found. Not_Found : exception; -- Identifies an invalid event. Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Invalid_Event; Props : ASF.Applications.Config; end record; -- The index of the last event definition. Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Applications; -- == Introduction == -- The <b>AWA.Events</b> package defines an event framework for modules to post events -- and have Ada bean methods be invoked when these events are dispatched. Subscription to -- events is done through configuration files. This allows to configure the modules and -- integrate them together easily at configuration time. -- -- === Declaration === -- Modules define the events that they can generate by instantiating the <b>Definition</b> -- package. This is a static definition of the event. Each event is given a unique name. -- -- package Event_New_User is new AWA.Events.Definition ("new-user"); -- -- === Posting an event === -- The module can post an event to inform other modules or the system that a particular -- action occurred. The module creates the event instance of type <b>Module_Event</b> and -- populates that event with useful properties for event receivers. -- -- Event : AWA.Events.Module_Event; -- -- Event.Set_Event_Kind (Event_New_User.Kind); -- Event.Set_Parameter ("email", "[email protected]"); -- -- The module will post the event by using the <b>Send_Event</b> operation. -- -- Manager.Send_Event (Event); -- -- === Receiving an event === -- Modules or applications interested by a particular event will configure the event manager -- to dispatch the event to an Ada bean event action. The Ada bean is an object that must -- implement a procedure that matches the prototype: -- -- type Action_Bean is new Util.Beans.Basic.Readonly_Bean ...; -- procedure Action (Bean : in out Action_Bean; Event : in AWA.Events.Module_Event'Class); -- -- The Ada bean method and object are registered as other Ada beans. -- -- The configuration file indicates how to bind the Ada bean action and the event together. -- The action is specified using an EL Method Expression (See Ada EL or JSR 245). -- -- <on-event name="new_user"> -- <action>#{ada_bean.action}</action> -- </on-event> -- -- === Event queues and dispatchers === -- The *AWA.Events* framework posts events on queues and it uses a dispatcher to process them. -- There are two kinds of dispatchers: -- -- * Synchronous dispatcher process the event when it is posted. The task which posts -- the event invokes the Ada bean action. In this dispatching mode, there is no event queue. -- If the action method raises an exception, it will however be blocked. -- -- * Asynchronous dispatcher are executed by dedicated tasks. The event is put in an event -- queue. A dispatcher task processes the event and invokes the action method at a later -- time. -- -- When the event is queued, there are two types of event queues: -- -- * A Fifo memory queue manages the event and dispatches them in FIFO order. -- If the application is stopped, the events present in the Fifo queue are lost. -- -- * A persistent event queue manages the event in a similar way as the FIFO queue but -- saves them in the database. If the application is stopped, events that have not yet -- been processed will be dispatched when the application is started again. -- -- == Data Model == -- @include Queues.hbm.xml -- package AWA.Events is type Queue_Index is new Natural; type Event_Index is new Natural; -- ------------------------------ -- Event kind definition -- ------------------------------ -- This package must be instantiated for each event that a module can post. generic Name : String; package Definition is function Kind return Event_Index; pragma Inline_Always (Kind); end Definition; -- Exception raised if an event name is not found. Not_Found : exception; -- Identifies an invalid event. Invalid_Event : constant Event_Index := 0; -- Find the event runtime index given the event name. -- Raises Not_Found exception if the event name is not recognized. function Find_Event_Index (Name : in String) return Event_Index; -- ------------------------------ -- Module event -- ------------------------------ type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; type Module_Event_Access is access all Module_Event'Class; -- Set the event type which identifies the event. procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index); -- Get the event type which identifies the event. function Get_Event_Kind (Event : in Module_Event) return Event_Index; -- Set a parameter on the message. procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Event : in Module_Event; Name : in String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object; private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Kind : Event_Index := Invalid_Event; Props : ASF.Applications.Config; end record; -- The index of the last event definition. Last_Event : Event_Index := 0; -- Get the event type name. function Get_Event_Type_Name (Index : in Event_Index) return Util.Strings.Name_Access; -- Make and return a copy of the event. function Copy (Event : in Module_Event) return Module_Event_Access; end AWA.Events;
Document the event queues and dispatchers
Document the event queues and dispatchers
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9a25f85d695c1ee284419ee88e7529bbe61d69d9
src/security-oauth-clients.ads
src/security-oauth-clients.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- 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; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; -- ------------------------------ -- 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; -- Get the application identifier. function Get_Application_Identifier (App : in Application) return String; -- 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; Refresh : in String; Id_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 OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_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, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- 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; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; -- ------------------------------ -- 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 new Security.OAuth.Application with private; -- Get the application identifier. function Get_Application_Identifier (App : in Application) return String; -- 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; Refresh : in String; Id_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 OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_Len); end record; type Application is new Security.OAuth.Application with record 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;
Move the definition of Application type to the Security.OAuth package. Extend the Application for OAuth.Clients specific needs
Move the definition of Application type to the Security.OAuth package. Extend the Application for OAuth.Clients specific needs
Ada
apache-2.0
stcarrez/ada-security
201dd252ddd3b3f67c83d2acee4a69ef9d2c8526
src/security-oauth-servers.ads
src/security-oauth-servers.ads
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- The OAuth 2.0 Authorization Framework. -- -- The authorization method produce a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Authorize (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identifies the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Auth : Security.Principal_Access; -- Token : String := ...; -- -- Realm.Authenticate (Token, Auth); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
----------------------------------------------------------------------- -- security-oauth-servers -- OAuth Server Authentication Support -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Strings; with Security.Auth; with Security.Permissions; -- == OAuth Server == -- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package. -- This package allows to implement the authorization framework described in RFC 6749 -- "The OAuth 2.0 Authorization Framework". -- -- The authorization method produces a <tt>Grant_Type</tt> object that contains the result -- of the grant (successful or denied). It is the responsibility of the caller to format -- the result in JSON/XML and return it to the client. -- -- Three important operations are defined for the OAuth 2.0 framework. They will be used -- in the following order: -- -- <tt>Authorize</tt> is used to obtain an authorization request. This operation is -- optional in the OAuth 2.0 framework since some authorization method directly return -- the access token. This operation is used by the "Authorization Code Grant" and the -- "Implicit Grant". -- -- <tt>Token</tt> is used to get the access token and optional refresh token. Each time it -- is called, a new token is generated. -- -- <tt>Authenticate</tt> is used for the API request to verify the access token -- and authenticate the API call. This operation can be called several times with the same -- token until the token is revoked or it has expired. -- -- Several grant types are supported. -- -- === Application Manager === -- The application manager maintains the repository of applications which are known by -- the server and which can request authorization. Each application is identified by -- a client identifier (represented by the <tt>client_id</tt> request parameter). -- The application defines the authorization methods which are allowed as well as -- the parameters to control and drive the authorization. This includes the redirection -- URI, the application secret, the expiration delay for the access token. -- -- The application manager is implemented by the application server and it must -- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt> -- method. The <tt>Find_Application</tt> is one of the first call made during the -- authenticate and token generation phases. -- -- === Resource Owner Password Credentials Grant === -- The password grant is one of the easiest grant method to understand but it is also one -- of the less secure. In this grant method, the username and user password are passed in -- the request parameter together with the application client identifier. The realm verifies -- the username and password and when they are correct it generates the access token with -- an optional refresh token. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- -- Realm.Token (Params, Grant); -- -- === Accessing Protected Resources === -- When accessing a protected resource, the API implementation will use the -- <tt>Authenticate</tt> operation to verify the access token and get a security principal. -- The security principal will identify the resource owner as well as the application -- that is doing the call. -- -- Realm : Security.OAuth.Servers.Auth_Manager; -- Grant : Security.OAuth.Servers.Grant_Type; -- Token : String := ...; -- -- Realm.Authenticate (Token, Grant); -- -- When a security principal is returned, the access token was validated and the -- request is granted for the application. -- package Security.OAuth.Servers is Invalid_Application : exception; type Application is new Security.OAuth.Application with private; -- Check if the application has the given permission. function Has_Permission (App : in Application; Permission : in Security.Permissions.Permission_Index) return Boolean; -- Define the status of the grant. type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant, Stealed_Grant, Valid_Grant); -- Define the grant type. type Grant_Kind is (No_Grant, Access_Grant, Code_Grant, Implicit_Grant, Password_Grant, Credential_Grant, Extension_Grant); -- The <tt>Grant_Type</tt> holds the results of the authorization. -- When the grant is refused, the type holds information about the refusal. type Grant_Type is record -- The request grant type. Request : Grant_Kind := No_Grant; -- The response status. Status : Grant_Status := Invalid_Grant; -- When success, the token to return. Token : Ada.Strings.Unbounded.Unbounded_String; -- When success, the token expiration date. Expires : Ada.Calendar.Time; -- When success, the authentication principal. Auth : Security.Principal_Access; -- When error, the type of error to return. Error : Util.Strings.Name_Access; end record; type Application_Manager is limited interface; type Application_Manager_Access is access all Application_Manager'Class; -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. function Find_Application (Realm : in Application_Manager; Client_Id : in String) return Application'Class is abstract; type Realm_Manager is limited interface; type Realm_Manager_Access is access all Realm_Manager'Class; -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. procedure Authenticate (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is abstract; -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. function Authorize (Realm : in Realm_Manager; App : in Application'Class; Scope : in String; Auth : in Principal_Access) return String is abstract; procedure Verify (Realm : in out Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is abstract; procedure Verify (Realm : in out Realm_Manager; Token : in String; Auth : out Principal_Access) is abstract; procedure Revoke (Realm : in out Realm_Manager; Auth : in Principal_Access) is abstract; type Auth_Manager is tagged limited private; type Auth_Manager_Access is access all Auth_Manager'Class; -- Set the auth private key. procedure Set_Private_Key (Manager : in out Auth_Manager; Key : in String); -- Set the application manager to use and and applications. procedure Set_Application_Manager (Manager : in out Auth_Manager; Repository : in Application_Manager_Access); -- Set the realm manager to authentify users. procedure Set_Realm_Manager (Manager : in out Auth_Manager; Realm : in Realm_Manager_Access); -- Authorize the access to the protected resource by the application and for the -- given principal. The resource owner has been verified and is represented by the -- <tt>Auth</tt> principal. Extract from the request parameters represented by -- <tt>Params</tt> the application client id, the scope and the expected response type. -- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749. procedure Authorize (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Token (Realm : in out Auth_Manager; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- Make the access token from the authorization code that was created by the -- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the -- client secret and the validity of the authorization code. Extract from the -- authorization code the auth principal that was used for the grant and make the -- access token. procedure Token_From_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); procedure Authorize_Code (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); procedure Authorize_Token (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Auth : in Security.Principal_Access; Grant : out Grant_Type); -- Make the access token from the resource owner password credentials. The username, -- password and scope are extracted from the request and they are verified through the -- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the -- principal describes the authorization and it is used to forge the access token. -- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant. procedure Token_From_Password (Realm : in out Auth_Manager; App : in Application'Class; Params : in Security.Auth.Parameters'Class; Grant : out Grant_Type); -- RFC 6749: 5. Issuing an Access Token procedure Create_Token (Realm : in Auth_Manager; Ident : in String; Grant : in out Grant_Type); -- Authenticate the access token and get a security principal that identifies the app/user. -- See RFC 6749, 7. Accessing Protected Resources. -- The access token is first searched in the cache. If it was found, it means the access -- token was already verified in the past, it is granted and associated with a principal. -- Otherwise, we have to verify the token signature first, then the expiration date and -- we extract from the token public part the auth identification. The <tt>Authenticate</tt> -- operation is then called to obtain the principal from the auth identification. -- When access token is invalid or authentification cannot be verified, a null principal -- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason -- of failures (if any). procedure Authenticate (Realm : in out Auth_Manager; Token : in String; Grant : out Grant_Type); procedure Revoke (Realm : in out Auth_Manager; Token : in String); private use Ada.Strings.Unbounded; function Format_Expire (Expire : in Ada.Calendar.Time) return String; type Application is new Security.OAuth.Application with record Expire_Timeout : Duration := 3600.0; Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET; end record; type Cache_Entry is record Expire : Ada.Calendar.Time; Auth : Principal_Access; end record; package Cache_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Cache_Entry, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- The access token cache is used to speed up the access token verification -- when a request to a protected resource is made. protected type Token_Cache is procedure Authenticate (Token : in String; Grant : in out Grant_Type); procedure Insert (Token : in String; Expire : in Ada.Calendar.Time; Principal : in Principal_Access); procedure Remove (Token : in String); procedure Timeout; private Entries : Cache_Map.Map; end Token_Cache; type Auth_Manager is new Ada.Finalization.Limited_Controlled with record -- The repository of applications. Repository : Application_Manager_Access; -- The realm for user authentication. Realm : Realm_Manager_Access; -- The server private key used by the HMAC signature. Private_Key : Ada.Strings.Unbounded.Unbounded_String; -- The access token cache. Cache : Token_Cache; -- The expiration time for the generated authorization code. Expire_Code : Duration := 300.0; end record; -- The <tt>Token_Validity</tt> record provides information about a token to find out -- the different components it is made of and verify its validity. The <tt>Validate</tt> -- procedure is in charge of checking the components and verifying the HMAC signature. -- The token has the following format: -- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>) type Token_Validity is record Status : Grant_Status := Invalid_Grant; Ident_Start : Natural := 0; Ident_End : Natural := 0; Expire : Ada.Calendar.Time; end record; function Validate (Realm : in Auth_Manager; Client_Id : in String; Token : in String) return Token_Validity; end Security.OAuth.Servers;
Update and correct the documentation
Update and correct the documentation
Ada
apache-2.0
stcarrez/ada-security
4111100b4647ecf60bf285db702e79b13c544db2
src/wiki-filters-variables.ads
src/wiki-filters-variables.ads
----------------------------------------------------------------------- -- wiki-filters-variables -- Expand variables in text and links -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Ada.Containers.Indefinite_Ordered_Maps; -- === Variables Filters === -- The `Wiki.Filters.Variables` package defines a filter that replaces variables -- in the text, links, quotes. Variables are represented as `$name`, `$(name)` -- or `${name}`. When a variable is not found, the original string is not modified. -- The list of variables is either configured programatically through the -- `Add_Variable` procedures but it can also be set from the Wiki text by using -- the `Wiki.Plugins.Variables` plugin. -- -- The variable filter must be configured with the plugin by declaring the instance: -- -- F : aliased Wiki.Filters.Html.Html_Filter_Type; -- -- Engine.Add_Filter (F'Unchecked_Access); -- -- And variables can be inserted by using the `Add_Variable` procedure: -- -- F.Add_Variable ("username", "gandalf"); -- package Wiki.Filters.Variables is pragma Preelaborate; type Variable_Filter is new Filter_Type with private; type Variable_Filter_Access is access all Variable_Filter'Class; -- Add a variable to replace the given name by its value. procedure Add_Variable (Filter : in out Variable_Filter; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); procedure Add_Variable (Filter : in out Variable_Filter; Name : in String; Value : in Wiki.Strings.WString); procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Add a section header with the given level in the document. overriding procedure Add_Header (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a text content with the given format to the document. Replace variables -- that are contained in the text. overriding procedure Add_Text (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a link. overriding procedure Add_Link (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. overriding procedure Add_Quote (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Expand the variables contained in the text. function Expand (Filter : in Variable_Filter; Text : in Wiki.Strings.WString) return Wiki.Strings.WString; -- Iterate over the filter variables. procedure Iterate (Filter : in Variable_Filter; Process : not null access procedure (Name, Value : in Strings.WString)); procedure Iterate (Chain : in Wiki.Filters.Filter_Chain; Process : not null access procedure (Name, Value : in Strings.WString)); private package Variable_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Strings.WString, Element_Type => Strings.WString); subtype Variable_Map is Variable_Maps.Map; subtype Variable_Cursor is Variable_Maps.Cursor; type Variable_Filter is new Filter_Type with record Variables : Variable_Map; end record; end Wiki.Filters.Variables;
----------------------------------------------------------------------- -- wiki-filters-variables -- Expand variables in text and links -- Copyright (C) 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. ----------------------------------------------------------------------- -- === Variables Filters === -- The `Wiki.Filters.Variables` package defines a filter that replaces variables -- in the text, links, quotes. Variables are represented as `$name`, `$(name)` -- or `${name}`. When a variable is not found, the original string is not modified. -- The list of variables is either configured programatically through the -- `Add_Variable` procedures but it can also be set from the Wiki text by using -- the `Wiki.Plugins.Variables` plugin. -- -- The variable filter must be configured with the plugin by declaring the instance: -- -- F : aliased Wiki.Filters.Html.Html_Filter_Type; -- -- Engine.Add_Filter (F'Unchecked_Access); -- -- And variables can be inserted by using the `Add_Variable` procedure: -- -- F.Add_Variable ("username", "gandalf"); -- package Wiki.Filters.Variables is type Variable_Filter is new Filter_Type with private; type Variable_Filter_Access is access all Variable_Filter'Class; -- Add a variable to replace the given name by its value. procedure Add_Variable (Filter : in out Variable_Filter; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); procedure Add_Variable (Filter : in out Variable_Filter; Name : in String; Value : in Wiki.Strings.WString); procedure Add_Variable (Chain : in Wiki.Filters.Filter_Chain; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Add a section header with the given level in the document. overriding procedure Add_Header (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Add a text content with the given format to the document. Replace variables -- that are contained in the text. overriding procedure Add_Text (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a link. overriding procedure Add_Link (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. overriding procedure Add_Quote (Filter : in out Variable_Filter; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Expand the variables contained in the text. function Expand (Filter : in Variable_Filter; Text : in Wiki.Strings.WString) return Wiki.Strings.WString; -- Iterate over the filter variables. procedure Iterate (Filter : in Variable_Filter; Process : not null access procedure (Name, Value : in Strings.WString)); procedure Iterate (Chain : in Wiki.Filters.Filter_Chain; Process : not null access procedure (Name, Value : in Strings.WString)); private subtype Variable_Map is Wiki.Strings.Maps.Map; subtype Variable_Cursor is Wiki.Strings.Maps.Cursor; type Variable_Filter is new Filter_Type with record Variables : Variable_Map; end record; end Wiki.Filters.Variables;
Update to use the Wiki.Strings.Maps map
Update to use the Wiki.Strings.Maps map
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
53c8c1b0669a42e02a0536c73148276655d734eb
regtests/util-streams-tests.adb
regtests/util-streams-tests.adb
----------------------------------------------------------------------- -- util-streams-tests -- Unit tests for encoding buffered streams -- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.Base64; with Util.Streams.AES; with Ada.IO_Exceptions; with Ada.Streams.Stream_IO; package body Util.Streams.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.AES"); generic Mode : in Util.Encoders.AES.AES_Mode; Label : in String; procedure Test_AES_Mode (T : in out Test); procedure Test_AES (T : in out Test; Item : in String; Count : in Positive; Mode : in Util.Encoders.AES.AES_Mode; Label : in String) is Reader : aliased Util.Streams.Texts.Reader_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Key : Util.Encoders.Secret_Key := Util.Encoders.Create ("0123456789abcdef0123456789abcdef"); begin -- Print -> Cipher -> Decipher Decipher.Initialize (64 * 1024); Decipher.Set_Key (Key, Mode); Cipher.Initialize (Decipher'Access, 1024); Cipher.Set_Key (Key, Mode); Print.Initialize (Cipher'Access); for I in 1 .. Count loop Print.Write (Item); end loop; Print.Flush; Util.Tests.Assert_Equals (T, Item'Length * Count, Decipher.Get_Size, Label & ": decipher buffer has the wrong size mode"); -- Read content in Decipher Reader.Initialize (Decipher); for I in 1 .. Count loop declare L : String (Item'Range) := (others => ' '); begin for J in L'Range loop Reader.Read (L (J)); end loop; Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value"); exception when Ada.IO_Exceptions.Data_Error => Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value (DATA error)"); end; end loop; end Test_AES; procedure Test_AES_Mode (T : in out Test) is begin for I in 1 .. 128 loop Test_AES (T, "a", I, Mode, Label); end loop; for I in 1 .. 128 loop Test_AES (T, "ab", I, Mode, Label); end loop; for I in 1 .. 128 loop Test_AES (T, "abc", I, Mode, Label); end loop; end Test_AES_Mode; procedure Test_AES_ECB is new Test_AES_Mode (Mode => Util.Encoders.AES.ECB, Label => "AES-ECB"); procedure Test_AES_CBC is new Test_AES_Mode (Mode => Util.Encoders.AES.CBC, Label => "AES-CBC"); procedure Test_AES_PCBC is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-PCBC"); procedure Test_AES_CFB is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CFB"); procedure Test_AES_OFB is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-OFB"); procedure Test_AES_CTR is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CTR"); procedure Test_Base64_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Base64.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("test-stream.b64"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64"); begin Print.Initialize (Output => Buffer'Access, Size => 5); Buffer.Initialize (Output => Stream'Access, Size => 1024); Stream.Create (Mode => Out_File, Name => Path); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "Base64 stream"); end Test_Base64_Stream; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Base64.Write, Read", Test_Base64_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-ECB)", Test_AES_ECB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CBC)", Test_AES_CBC'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-PCBC)", Test_AES_PCBC'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CFB)", Test_AES_CFB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-OFB)", Test_AES_OFB'Access); Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CTR)", Test_AES_CTR'Access); end Add_Tests; end Util.Streams.Tests;
----------------------------------------------------------------------- -- util-streams-tests -- Unit tests for encoding buffered streams -- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.Base64; with Util.Streams.AES; with Util.Measures; with Ada.IO_Exceptions; with Ada.Streams.Stream_IO; package body Util.Streams.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; package AES_Caller is new Util.Test_Caller (Test, "Streams.AES"); package Caller is new Util.Test_Caller (Test, "Streams.Main"); generic Mode : in Util.Encoders.AES.AES_Mode; Label : in String; procedure Test_AES_Mode (T : in out Test); procedure Test_AES (T : in out Test; Item : in String; Count : in Positive; Mode : in Util.Encoders.AES.AES_Mode; Label : in String) is Reader : aliased Util.Streams.Texts.Reader_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Key : Util.Encoders.Secret_Key := Util.Encoders.Create ("0123456789abcdef0123456789abcdef"); begin -- Print -> Cipher -> Decipher Decipher.Initialize (64 * 1024); Decipher.Set_Key (Key, Mode); Cipher.Initialize (Decipher'Access, 1024); Cipher.Set_Key (Key, Mode); Print.Initialize (Cipher'Access); for I in 1 .. Count loop Print.Write (Item); end loop; Print.Flush; Util.Tests.Assert_Equals (T, Item'Length * Count, Decipher.Get_Size, Label & ": decipher buffer has the wrong size mode"); -- Read content in Decipher Reader.Initialize (Decipher); for I in 1 .. Count loop declare L : String (Item'Range) := (others => ' '); begin for J in L'Range loop Reader.Read (L (J)); end loop; Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value"); exception when Ada.IO_Exceptions.Data_Error => Util.Tests.Assert_Equals (T, Item, L, Label & ": wrong value (DATA error)"); end; end loop; end Test_AES; procedure Test_AES_Mode (T : in out Test) is begin for I in 1 .. 128 loop Test_AES (T, "a", I, Mode, Label); end loop; for I in 1 .. 128 loop Test_AES (T, "ab", I, Mode, Label); end loop; for I in 1 .. 128 loop Test_AES (T, "abc", I, Mode, Label); end loop; end Test_AES_Mode; procedure Test_AES_ECB is new Test_AES_Mode (Mode => Util.Encoders.AES.ECB, Label => "AES-ECB"); procedure Test_AES_CBC is new Test_AES_Mode (Mode => Util.Encoders.AES.CBC, Label => "AES-CBC"); procedure Test_AES_PCBC is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-PCBC"); procedure Test_AES_CFB is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CFB"); procedure Test_AES_OFB is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-OFB"); procedure Test_AES_CTR is new Test_AES_Mode (Mode => Util.Encoders.AES.PCBC, Label => "AES-CTR"); procedure Test_Base64_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Base64.Encoding_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("test-stream.b64"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64"); begin Print.Initialize (Output => Buffer'Access, Size => 5); Buffer.Initialize (Output => Stream'Access, Size => 1024); Stream.Create (Mode => Out_File, Name => Path); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "Base64 stream"); end Test_Base64_Stream; procedure Test_Copy_Stream (T : in out Test) is use type Ada.Streams.Stream_Element_Offset; Pat : constant String := "123456789abcdef0123456789"; Buf : Ada.Streams.Stream_Element_Array (1 .. Pat'Length); Res : String (10 .. 10 + Pat'Length - 1); begin declare S : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Util.Streams.Copy (Pat, Buf); end loop; Util.Measures.Report (S, "Util.Streams.Copy (String)", 1000); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Util.Streams.Copy (Buf, Res); end loop; Util.Measures.Report (S, "Util.Streams.Copy (Stream_Element_Array)", 1000); end; Util.Tests.Assert_Equals (T, Pat, Res, "Invalid copy"); end Test_Copy_Stream; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Copy", Test_Copy_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Base64.Write, Read", Test_Base64_Stream'Access); AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-ECB)", Test_AES_ECB'Access); AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CBC)", Test_AES_CBC'Access); AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-PCBC)", Test_AES_PCBC'Access); AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CFB)", Test_AES_CFB'Access); AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-OFB)", Test_AES_OFB'Access); AES_Caller.Add_Test (Suite, "Test Util.Streams.AES (AES-CTR)", Test_AES_CTR'Access); end Add_Tests; end Util.Streams.Tests;
Implement the Test_Copy_Stream procedure and register it for execution
Implement the Test_Copy_Stream procedure and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b3103bfca32c9066b1b31b09be135abb2f53b8ec
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "34"; copyright_years : constant String := "2015-2019"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.30"; default_pgsql : constant String := "11"; default_php : constant String := "7.3"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.3.0"; previous_compiler : constant String := "8.2.0"; binutils_version : constant String := "2.32"; previous_binutils : constant String := "2.31.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "34"; copyright_years : constant String := "2015-2019"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.30"; default_pgsql : constant String := "11"; default_php : constant String := "7.3"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.3.0"; previous_compiler : constant String := "8.2.0"; binutils_version : constant String := "2.33.1"; previous_binutils : constant String := "2.32"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
switch to latest binutils
switch to latest binutils
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
13c80051e40eaefebadeab7c8b5d4491d64d8a4c
src/el-contexts.ads
src/el-contexts.ads
----------------------------------------------------------------------- -- EL.Contexts -- Contexts for evaluating an expression -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The expression context provides information to resolve runtime -- information when evaluating an expression. The context provides -- a resolver whose role is to find variables given their name. with EL.Objects; with Util.Beans.Basic; with Ada.Strings.Unbounded; with Ada.Exceptions; with EL.Functions; limited with EL.Variables; package EL.Contexts is pragma Preelaborate; use EL.Objects; use Ada.Strings.Unbounded; type ELContext; -- ------------------------------ -- Expression Resolver -- ------------------------------ -- Enables customization of variable and property resolution -- behavior for EL expression evaluation. type ELResolver is interface; type ELResolver_Access is access all ELResolver'Class; -- Get the value associated with a base object and a given property. function Get_Value (Resolver : ELResolver; Context : ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is abstract; -- Set the value associated with a base object and a given property. procedure Set_Value (Resolver : in out ELResolver; Context : in ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- Expression Context -- ------------------------------ -- Context information for expression evaluation. type ELContext is limited interface; type ELContext_Access is access all ELContext'Class; -- Retrieves the ELResolver associated with this ELcontext. function Get_Resolver (Context : ELContext) return ELResolver_Access is abstract; -- Retrieves the VariableMapper associated with this ELContext. function Get_Variable_Mapper (Context : ELContext) return access EL.Variables.Variable_Mapper'Class is abstract; -- Set the variable mapper associated with this ELContext. procedure Set_Variable_Mapper (Context : in out ELContext; Mapper : access EL.Variables.Variable_Mapper'Class) is abstract; -- Retrieves the FunctionMapper associated with this ELContext. -- The FunctionMapper is only used when parsing an expression. function Get_Function_Mapper (Context : ELContext) return EL.Functions.Function_Mapper_Access is abstract; -- Set the function mapper associated with this ELContext. procedure Set_Function_Mapper (Context : in out ELContext; Mapper : access EL.Functions.Function_Mapper'Class) is abstract; -- Handle the exception during expression evaluation. The handler can ignore the -- exception or raise it. procedure Handle_Exception (Context : in ELContext; Ex : in Ada.Exceptions.Exception_Occurrence) is abstract; end EL.Contexts;
----------------------------------------------------------------------- -- EL.Contexts -- Contexts for evaluating an expression -- 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. ----------------------------------------------------------------------- -- The expression context provides information to resolve runtime -- information when evaluating an expression. The context provides -- a resolver whose role is to find variables given their name. with EL.Objects; with Util.Beans.Basic; with Ada.Strings.Unbounded; with Ada.Exceptions; with EL.Functions; limited with EL.Variables; package EL.Contexts is pragma Preelaborate; use EL.Objects; use Ada.Strings.Unbounded; type ELContext; -- ------------------------------ -- Expression Resolver -- ------------------------------ -- Enables customization of variable and property resolution -- behavior for EL expression evaluation. type ELResolver is limited interface; type ELResolver_Access is access all ELResolver'Class; -- Get the value associated with a base object and a given property. function Get_Value (Resolver : ELResolver; Context : ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is abstract; -- Set the value associated with a base object and a given property. procedure Set_Value (Resolver : in out ELResolver; Context : in ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- Expression Context -- ------------------------------ -- Context information for expression evaluation. type ELContext is limited interface; type ELContext_Access is access all ELContext'Class; -- Retrieves the ELResolver associated with this ELcontext. function Get_Resolver (Context : ELContext) return ELResolver_Access is abstract; -- Retrieves the VariableMapper associated with this ELContext. function Get_Variable_Mapper (Context : ELContext) return access EL.Variables.Variable_Mapper'Class is abstract; -- Set the variable mapper associated with this ELContext. procedure Set_Variable_Mapper (Context : in out ELContext; Mapper : access EL.Variables.Variable_Mapper'Class) is abstract; -- Retrieves the FunctionMapper associated with this ELContext. -- The FunctionMapper is only used when parsing an expression. function Get_Function_Mapper (Context : ELContext) return EL.Functions.Function_Mapper_Access is abstract; -- Set the function mapper associated with this ELContext. procedure Set_Function_Mapper (Context : in out ELContext; Mapper : access EL.Functions.Function_Mapper'Class) is abstract; -- Handle the exception during expression evaluation. The handler can ignore the -- exception or raise it. procedure Handle_Exception (Context : in ELContext; Ex : in Ada.Exceptions.Exception_Occurrence) is abstract; end EL.Contexts;
Change the ELResolver to a limited interface
Change the ELResolver to a limited interface
Ada
apache-2.0
Letractively/ada-el
8e21178309a6b7f0898df561ff99e5289362f812
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Send; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Into.Module.Get_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; begin Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "user_id", Value => User); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Into.Module.Get_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; begin Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "user_id", Value => User); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
Implement the Create_Invitation_Bean function
Implement the Create_Invitation_Bean function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
747862c6b8b7cc6b619dc48b43f6801e65a2450c
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; end record; -- Load the list of members. overriding procedure Load (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); end AWA.Workspaces.Beans;
Declare the Member_List_Bean type and override the Load procedure
Declare the Member_List_Bean type and override the Load procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
53b9c9b0f3b38b8b2f261aa076969fe699d5b4e4
src/util-stacks.ads
src/util-stacks.ads
----------------------------------------------------------------------- -- util-stacks -- Simple stack -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; generic type Element_Type is private; type Element_Type_Access is access all Element_Type; package Util.Stacks is type Stack is limited private; -- Get access to the current stack element. function Current (Container : in Stack) return Element_Type_Access; -- Push an element on top of the stack making the new element the current one. procedure Push (Container : in out Stack); -- Pop the top element. procedure Pop (Container : in out Stack); -- Clear the stack. procedure Clear (Container : in out Stack); private type Element_Type_Array is array (Natural range <>) of aliased Element_Type; type Element_Type_Array_Access is access all Element_Type_Array; type Stack is new Ada.Finalization.Limited_Controlled with record Current : Element_Type_Access := null; Stack : Element_Type_Array_Access := null; Pos : Natural := 0; end record; -- Release the stack overriding procedure Finalize (Obj : in out Stack); end Util.Stacks;
----------------------------------------------------------------------- -- util-stacks -- Simple stack -- Copyright (C) 2010, 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.Finalization; generic type Element_Type is private; type Element_Type_Access is access all Element_Type; package Util.Stacks is pragma Preelaborate; type Stack is limited private; -- Get access to the current stack element. function Current (Container : in Stack) return Element_Type_Access; -- Push an element on top of the stack making the new element the current one. procedure Push (Container : in out Stack); -- Pop the top element. procedure Pop (Container : in out Stack); -- Clear the stack. procedure Clear (Container : in out Stack); private type Element_Type_Array is array (Natural range <>) of aliased Element_Type; type Element_Type_Array_Access is access all Element_Type_Array; type Stack is new Ada.Finalization.Limited_Controlled with record Current : Element_Type_Access := null; Stack : Element_Type_Array_Access := null; Pos : Natural := 0; end record; -- Release the stack overriding procedure Finalize (Obj : in out Stack); end Util.Stacks;
Make the package Preelaborate
Make the package Preelaborate
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
36443960c2f7e51aaed7f8d7b12a74a251516614
src/util-serialize-tools.adb
src/util-serialize-tools.adb
----------------------------------------------------------------------- -- util-serialize-tools -- Tools to Serialize objects in various formats -- Copyright (C) 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.Mappers.Record_Mapper; package body Util.Serialize.Tools is type Object_Field is (FIELD_NAME, FIELD_VALUE); type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class; type Object_Mapper_Context is record Map : Object_Map_Access; Name : Util.Beans.Objects.Object; end record; type Object_Mapper_Context_Access is access all Object_Mapper_Context; procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_VALUE => Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value); Into.Name := Util.Beans.Objects.Null_Object; end case; end Set_Member; package Object_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context, Element_Type_Access => Object_Mapper_Context_Access, Fields => Object_Field, Set_Member => Set_Member); JSON_Mapping : aliased Object_Mapper.Mapper; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b> -- JSON stream. Use the <b>Name</b> as the name of the JSON object. -- ----------------------- procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream'Class; Name : in String; Map : in Util.Beans.Objects.Maps.Map) is use type Ada.Containers.Count_Type; procedure Write (Name : in String; Value : in Util.Beans.Objects.Object); procedure Write (Name : in String; Value : in Util.Beans.Objects.Object) is begin Output.Start_Entity (Name => ""); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_Attribute (Name => "value", Value => Value); Output.End_Entity (Name => ""); end Write; begin if Map.Length > 0 then declare Iter : Util.Beans.Objects.Maps.Cursor := Map.First; begin Output.Start_Array (Name => Name); while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access); Util.Beans.Objects.Maps.Next (Iter); end loop; Output.End_Array (Name => Name); end; end if; end To_JSON; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into an XML stream. -- Returns the JSON string that contains a serialization of the object maps. -- ----------------------- function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is use type Ada.Containers.Count_Type; begin if Map.Length = 0 then return ""; end if; declare Buffer : aliased Util.Streams.Texts.Print_Stream; Output : Util.Serialize.IO.JSON.Output_Stream; begin Buffer.Initialize (Size => 10000); Output.Initialize (Buffer'Unchecked_Access); Output.Start_Document; To_JSON (Output, "params", Map); Output.End_Document; return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Buffer)); end; end To_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. The object map passed in <b>Map</b> can contain existing values. -- They will be overriden by the JSON values. -- ----------------------- procedure From_JSON (Content : in String; Map : in out Util.Beans.Objects.Maps.Map) is Parser : Util.Serialize.IO.JSON.Parser; Context : aliased Object_Mapper_Context; begin if Content'Length > 0 then Context.Map := Map'Unchecked_Access; Parser.Add_Mapping ("**", JSON_Mapping'Access); Object_Mapper.Set_Context (Parser, Context'Unchecked_Access); Parser.Parse_String (Content); end if; end From_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. -- Returns the object map that was restored. -- ----------------------- function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is Result : Util.Beans.Objects.Maps.Map; begin From_JSON (Content, Result); return Result; end From_JSON; begin JSON_Mapping.Add_Mapping ("name", FIELD_NAME); JSON_Mapping.Add_Mapping ("value", FIELD_VALUE); end Util.Serialize.Tools;
----------------------------------------------------------------------- -- util-serialize-tools -- Tools to Serialize objects in various formats -- Copyright (C) 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.Mappers.Record_Mapper; package body Util.Serialize.Tools is type Object_Field is (FIELD_NAME, FIELD_VALUE); type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class; type Object_Mapper_Context is record Map : Object_Map_Access; Name : Util.Beans.Objects.Object; end record; type Object_Mapper_Context_Access is access all Object_Mapper_Context; procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_VALUE => Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value); Into.Name := Util.Beans.Objects.Null_Object; end case; end Set_Member; package Object_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context, Element_Type_Access => Object_Mapper_Context_Access, Fields => Object_Field, Set_Member => Set_Member); JSON_Mapping : aliased Object_Mapper.Mapper; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b> -- JSON stream. Use the <b>Name</b> as the name of the JSON object. -- ----------------------- procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream'Class; Name : in String; Map : in Util.Beans.Objects.Maps.Map) is use type Ada.Containers.Count_Type; procedure Write (Name : in String; Value : in Util.Beans.Objects.Object); procedure Write (Name : in String; Value : in Util.Beans.Objects.Object) is begin Output.Start_Entity (Name => ""); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_Attribute (Name => "value", Value => Value); Output.End_Entity (Name => ""); end Write; begin if Map.Length > 0 then declare Iter : Util.Beans.Objects.Maps.Cursor := Map.First; begin Output.Start_Array (Name => Name); while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access); Util.Beans.Objects.Maps.Next (Iter); end loop; Output.End_Array (Name => Name); end; end if; end To_JSON; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into an XML stream. -- Returns the JSON string that contains a serialization of the object maps. -- ----------------------- function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is use type Ada.Containers.Count_Type; begin if Map.Length = 0 then return ""; end if; declare Buffer : aliased Util.Streams.Texts.Print_Stream; Output : Util.Serialize.IO.JSON.Output_Stream; begin Buffer.Initialize (Size => 10000); Output.Initialize (Buffer'Unchecked_Access); Output.Start_Document; To_JSON (Output, "params", Map); Output.End_Document; return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Buffer)); end; end To_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. The object map passed in <b>Map</b> can contain existing values. -- They will be overriden by the JSON values. -- ----------------------- procedure From_JSON (Content : in String; Map : in out Util.Beans.Objects.Maps.Map) is Parser : Util.Serialize.IO.JSON.Parser; Mapper : Util.Serialize.Mappers.Processing; Context : aliased Object_Mapper_Context; begin if Content'Length > 0 then Context.Map := Map'Unchecked_Access; Mapper.Add_Mapping ("**", JSON_Mapping'Access); Object_Mapper.Set_Context (Mapper, Context'Unchecked_Access); Parser.Parse_String (Content, Mapper); end if; end From_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. -- Returns the object map that was restored. -- ----------------------- function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is Result : Util.Beans.Objects.Maps.Map; begin From_JSON (Content, Result); return Result; end From_JSON; begin JSON_Mapping.Add_Mapping ("name", FIELD_NAME); JSON_Mapping.Add_Mapping ("value", FIELD_VALUE); end Util.Serialize.Tools;
Update the From_JSON operation for the new parser/mapper interfaces
Update the From_JSON operation for the new parser/mapper interfaces
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ee415d1907e06082bf63ec1e0d4433c2281aca91
src/wiki-streams-text_io.adb
src/wiki-streams-text_io.adb
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Wiki.Helpers; package body Wiki.Streams.Text_IO is -- ------------------------------ -- Open the file and prepare to read the input stream. -- ------------------------------ procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form); end Open; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Input_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Input_Stream) is begin Stream.Close; end Finalize; -- ------------------------------ -- Read one character from the input stream and return False to the <tt>Eof</tt> indicator. -- When there is no character to read, return True in the <tt>Eof</tt> indicator. -- ------------------------------ overriding procedure Read (Input : in out File_Input_Stream; Char : out Wiki.Strings.WChar; Eof : out Boolean) is Available : Boolean; begin Eof := False; Ada.Wide_Wide_Text_IO.Get_immediate (Input.File, Char, Available); exception when Ada.IO_Exceptions.End_Error => Char := Wiki.Helpers.LF; Eof := True; end Read; -- ------------------------------ -- Open the file and prepare to write the output stream. -- ------------------------------ procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Open; -- ------------------------------ -- Create the file and prepare to write the output stream. -- ------------------------------ procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Create; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Output_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Write the string to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Content); else Ada.Wide_Wide_Text_IO.Put (Content); end if; end Write; -- ------------------------------ -- Write a single character to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Char); else Ada.Wide_Wide_Text_IO.Put (Char); end if; end Write; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Output_Stream) is begin Stream.Close; end Finalize; end Wiki.Streams.Text_IO;
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Wiki.Helpers; package body Wiki.Streams.Text_IO is -- ------------------------------ -- Open the file and prepare to read the input stream. -- ------------------------------ procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form); end Open; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Input_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Input_Stream) is begin Stream.Close; end Finalize; -- ------------------------------ -- Read one character from the input stream and return False to the <tt>Eof</tt> indicator. -- When there is no character to read, return True in the <tt>Eof</tt> indicator. -- ------------------------------ overriding procedure Read (Input : in out File_Input_Stream; Char : out Wiki.Strings.WChar; Eof : out Boolean) is Available : Boolean; begin Eof := False; Ada.Wide_Wide_Text_IO.Get_Immediate (Input.File, Char, Available); exception when Ada.IO_Exceptions.End_Error => Char := Wiki.Helpers.LF; Eof := True; end Read; -- ------------------------------ -- Open the file and prepare to write the output stream. -- ------------------------------ procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Open; -- ------------------------------ -- Create the file and prepare to write the output stream. -- ------------------------------ procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Create; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Output_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Write the string to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Content); else Ada.Wide_Wide_Text_IO.Put (Content); end if; end Write; -- ------------------------------ -- Write a single character to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Char); else Ada.Wide_Wide_Text_IO.Put (Char); end if; end Write; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Output_Stream) is begin Stream.Close; end Finalize; end Wiki.Streams.Text_IO;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0a0e91b38aa4463a27353ebae93b31503c39d94a
src/wiki-streams-text_io.ads
src/wiki-streams-text_io.ads
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Wide_Wide_Text_IO; with Ada.Finalization; -- === Text_IO Input and Output streams === -- The `Wiki.Streams.Text_IO` package defines the `File_Input_Stream` and -- the `File_Output_Stream` types which use the `Ada.Wide_Wide_Text_IO` package -- to read or write the output streams. -- -- By default the `File_Input_Stream` is configured to read the standard input. -- The `Open` procedure can be used to read from a file knowing its name. -- -- The `File_Output_Stream` is configured to write on the standard output. -- The `Open` and `Create` procedure can be used to write on a file. -- package Wiki.Streams.Text_IO is type File_Input_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Input_Stream with private; type File_Input_Stream_Access is access all File_Input_Stream'Class; -- Open the file and prepare to read the input stream. procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := ""); -- Read one character from the input stream and return False to the <tt>Eof</tt> indicator. -- When there is no character to read, return True in the <tt>Eof</tt> indicator. overriding procedure Read (Input : in out File_Input_Stream; Char : out Wiki.Strings.WChar; Eof : out Boolean); -- Close the file. procedure Close (Stream : in out File_Input_Stream); -- Close the stream. overriding procedure Finalize (Stream : in out File_Input_Stream); type File_Output_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Output_Stream with private; type File_Output_Stream_Access is access all File_Output_Stream'Class; -- Open the file and prepare to write the output stream. procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := ""); -- Create the file and prepare to write the output stream. procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := ""); -- Close the file. procedure Close (Stream : in out File_Output_Stream); -- Write the string to the output stream. overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString); -- Write a single character to the output stream. overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar); -- Close the stream. overriding procedure Finalize (Stream : in out File_Output_Stream); private type File_Input_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Input_Stream with record File : Ada.Wide_Wide_Text_IO.File_Type; end record; type File_Output_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Output_Stream with record File : Ada.Wide_Wide_Text_IO.File_Type; Stdout : Boolean := True; end record; end Wiki.Streams.Text_IO;
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Wide_Wide_Text_IO; with Ada.Finalization; -- === Text_IO Input and Output streams === -- The `Wiki.Streams.Text_IO` package defines the `File_Input_Stream` and -- the `File_Output_Stream` types which use the `Ada.Wide_Wide_Text_IO` package -- to read or write the output streams. -- -- By default the `File_Input_Stream` is configured to read the standard input. -- The `Open` procedure can be used to read from a file knowing its name. -- -- The `File_Output_Stream` is configured to write on the standard output. -- The `Open` and `Create` procedure can be used to write on a file. -- package Wiki.Streams.Text_IO is type File_Input_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Input_Stream with private; type File_Input_Stream_Access is access all File_Input_Stream'Class; -- Open the file and prepare to read the input stream. procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := ""); -- Read the input stream and fill the `Into` buffer until either it is full or -- we reach the end of line. Returns in `Last` the last valid position in the -- `Into` buffer. When there is no character to read, return True in -- the `Eof` indicator. procedure Read (Input : in out File_Input_Stream; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean); -- Close the file. procedure Close (Stream : in out File_Input_Stream); -- Close the stream. overriding procedure Finalize (Stream : in out File_Input_Stream); type File_Output_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Output_Stream with private; type File_Output_Stream_Access is access all File_Output_Stream'Class; -- Open the file and prepare to write the output stream. procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := ""); -- Create the file and prepare to write the output stream. procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := ""); -- Close the file. procedure Close (Stream : in out File_Output_Stream); -- Write the string to the output stream. overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString); -- Write a single character to the output stream. overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar); -- Close the stream. overriding procedure Finalize (Stream : in out File_Output_Stream); private type File_Input_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Input_Stream with record File : Ada.Wide_Wide_Text_IO.File_Type; end record; type File_Output_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Output_Stream with record File : Ada.Wide_Wide_Text_IO.File_Type; Stdout : Boolean := True; end record; end Wiki.Streams.Text_IO;
Update the Read procedure to read a complete line
Update the Read procedure to read a complete line
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
cd175e799b4659427259f2b034f0a08d81ba3114
src/gen-generator.ads
src/gen-generator.ads
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; package Gen.Generator is -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in Ada.Strings.Unbounded.Unbounded_String; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in String); -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : Unbounded_String; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Output base directory. Output_Dir : Ada.Strings.Unbounded.Unbounded_String; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : access Util.Beans.Objects.Object; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : access Util.Beans.Objects.Object; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : access Util.Beans.Objects.Object; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; package Gen.Generator is -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in Ada.Strings.Unbounded.Unbounded_String; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in String); -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : Unbounded_String; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Output base directory. Output_Dir : Ada.Strings.Unbounded.Unbounded_String; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : access Util.Beans.Objects.Object; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : access Util.Beans.Objects.Object; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : access Util.Beans.Objects.Object; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
Define the G_URI namespace in the package specification for use by the template command
Define the G_URI namespace in the package specification for use by the template command
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
19eafc10c1ed38d76667ca572c9bd115d895ada7
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key), Invitation => Bean); exception when others => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Send_Invitation (Bean); end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Into.Module.Get_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; begin Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "user_id", Value => User); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Events.Faces.Actions; with ADO.Utils; with ADO.Sessions.Entities; with ADO.Sessions; with ADO.Queries; with ADO.Datasets; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Events.Action_Method; with AWA.Services.Contexts; package body AWA.Workspaces.Beans is package ASC renames AWA.Services.Contexts; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key), Invitation => Bean); exception when others => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Accept_Invitation; overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Module.Send_Invitation (Bean); end Send; -- ------------------------------ -- Create the Invitation_Bean bean instance. -- ------------------------------ function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Invitation_Bean_Access := new Invitation_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Invitation_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; -- ------------------------------ -- Event action called to create the workspace when the given event is posted. -- ------------------------------ procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Bean, Event); WS : AWA.Workspaces.Models.Workspace_Ref; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (Session => DB, Context => Ctx, Workspace => WS); Ctx.Commit; end Create; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean, Method => Action, Name => "action"); package Create_Binding is new AWA.Events.Action_Method.Bind (Name => "create", Bean => Workspaces_Bean, Method => Create); Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Workspaces_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Workspaces_Bean_Access := new Workspaces_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Workspaces_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" then return Util.Beans.Objects.To_Object (Value => From.Members_Bean, Storage => Util.Beans.Objects.STATIC); else return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Load the list of members. -- ------------------------------ overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := Into.Module.Get_Session; Query : ADO.Queries.Context; Count_Query : ADO.Queries.Context; First : constant Natural := (Into.Page - 1) * Into.Page_Size; begin Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List); -- ADO.Sessions.Entities.Bind_Param (Params => Query, -- Name => "page_table", -- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, -- Session => Session); Query.Bind_Param (Name => "user_id", Value => User); Count_Query.Bind_Param (Name => "user_id", Value => User); AWA.Workspaces.Models.List (Into.Members, Session, Query); Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); end Load; -- ------------------------------ -- Create the Member_List_Bean bean instance. -- ------------------------------ function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Member_List_Bean_Access := new Member_List_Bean; begin Object.Module := Module; Object.Members_Bean := Object.Members'Access; Object.Page_Size := 20; Object.Page := 1; Object.Count := 0; return Object.all'Access; end Create_Member_List_Bean; end AWA.Workspaces.Beans;
Implement the Get_Value function
Implement the Get_Value function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e0c5c58aed435dbfaf64264ba6f23a10ef16ffed
src/asf-contexts-faces.ads
src/asf-contexts-faces.ads
----------------------------------------------------------------------- -- asf-contexts.faces -- Faces Contexts -- 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 ASF.Requests; with ASF.Responses; with ASF.Sessions; limited with ASF.Converters; with ASF.Components.Root; limited with ASF.Applications.Main; with ASF.Applications.Messages; with ASF.Applications.Messages.Vectors; with ASF.Contexts.Writer; with ASF.Contexts.Exceptions; limited with ASF.Contexts.Flash; with ASF.Events.Exceptions; with ASF.Events.Phases; with EL.Objects; with EL.Contexts; with Util.Locales; with Util.Beans.Basic; with Ada.Exceptions; with Ada.Strings.Unbounded; private with Ada.Finalization; private with Ada.Strings.Unbounded.Hash; private with Ada.Containers.Hashed_Maps; -- The <b>Faces_Context</b> is an object passed to the component tree and -- bean actions to provide the full context in which the view is rendered -- or evaluated. The faces context gives access to the bean variables, -- the request and its parameters, the response writer to write on the -- output stream. -- -- The <b>Faces_Context</b> is never shared: it is specific to each request. package ASF.Contexts.Faces is use Ada.Strings.Unbounded; type Application_Access is access all ASF.Applications.Main.Application'Class; type Flash_Context_Access is access all ASF.Contexts.Flash.Flash_Context'Class; type Faces_Context is tagged limited private; type Faces_Context_Access is access all Faces_Context'Class; -- Get the response writer to write the response stream. function Get_Response_Writer (Context : Faces_Context) return ASF.Contexts.Writer.Response_Writer_Access; -- Set the response writer to write to the response stream. procedure Set_Response_Writer (Context : in out Faces_Context; Writer : in ASF.Contexts.Writer.Response_Writer_Access); -- Get the EL context for evaluating expressions. function Get_ELContext (Context : in Faces_Context) return EL.Contexts.ELContext_Access; -- Set the EL context for evaluating expressions. procedure Set_ELContext (Context : in out Faces_Context; ELContext : in EL.Contexts.ELContext_Access); -- Set the attribute having given name with the value. procedure Set_Attribute (Context : in out Faces_Context; Name : in String; Value : in EL.Objects.Object); -- Set the attribute having given name with the value. procedure Set_Attribute (Context : in out Faces_Context; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the attribute with the given name. function Get_Attribute (Context : in Faces_Context; Name : in String) return EL.Objects.Object; -- Get the attribute with the given name. function Get_Attribute (Context : in Faces_Context; Name : in Unbounded_String) return EL.Objects.Object; -- Get the bean attribute with the given name. -- Returns null if the attribute does not exist or is not a bean. function Get_Bean (Context : in Faces_Context; Name : in String) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a request parameter function Get_Parameter (Context : Faces_Context; Name : String) return String; -- Get the session associated with the current faces context. function Get_Session (Context : in Faces_Context; Create : in Boolean := False) return ASF.Sessions.Session; -- Get the request function Get_Request (Context : Faces_Context) return ASF.Requests.Request_Access; -- Set the request procedure Set_Request (Context : in out Faces_Context; Request : in ASF.Requests.Request_Access); -- Get the response function Get_Response (Context : Faces_Context) return ASF.Responses.Response_Access; -- Set the response procedure Set_Response (Context : in out Faces_Context; Response : in ASF.Responses.Response_Access); -- Signal the JavaServer faces implementation that, as soon as the -- current phase of the request processing lifecycle has been completed, -- control should be passed to the <b>Render Response</b> phase, -- bypassing any phases that have not been executed yet. procedure Render_Response (Context : in out Faces_Context); -- Check whether the <b>Render_Response</b> phase must be processed immediately. function Get_Render_Response (Context : in Faces_Context) return Boolean; -- Signal the JavaServer Faces implementation that the HTTP response -- for this request has already been generated (such as an HTTP redirect), -- and that the request processing lifecycle should be terminated as soon -- as the current phase is completed. procedure Response_Completed (Context : in out Faces_Context); -- Check whether the response has been completed. function Get_Response_Completed (Context : in Faces_Context) return Boolean; -- Get the flash context allowing to add flash attributes. function Get_Flash (Context : in Faces_Context) return Flash_Context_Access; -- Set the flash context. procedure Set_Flash (Context : in out Faces_Context; Flash : in Flash_Context_Access); -- Append the message to the list of messages associated with the specified -- client identifier. If <b>Client_Id</b> is empty, the message is global -- (or not associated with a component) procedure Add_Message (Context : in out Faces_Context; Client_Id : in String; Message : in ASF.Applications.Messages.Message); -- Append the message to the list of messages associated with the specified -- client identifier. If <b>Client_Id</b> is empty, the message is global -- (or not associated with a component) procedure Add_Message (Context : in out Faces_Context; Client_Id : in String; Message : in String; Severity : in Applications.Messages.Severity := Applications.Messages.ERROR); -- Append the messages defined in <b>Messages</b> to the current list of messages -- in the faces context. procedure Add_Messages (Context : in out Faces_Context; Client_Id : in String; Messages : in ASF.Applications.Messages.Vectors.Vector); -- Get an iterator for the messages associated with the specified client -- identifier. If the <b>Client_Id</b> ie empty, an iterator for the -- global messages is returned. function Get_Messages (Context : in Faces_Context; Client_Id : in String) return ASF.Applications.Messages.Vectors.Cursor; -- Returns the maximum severity level recorded for any message that has been queued. -- Returns NONE if no message has been queued. function Get_Maximum_Severity (Context : in Faces_Context) return ASF.Applications.Messages.Severity; -- Get a converter from a name. -- Returns the converter object or null if there is no converter. function Get_Converter (Context : in Faces_Context; Name : in EL.Objects.Object) return access ASF.Converters.Converter'Class; -- Get the application associated with this faces context. function Get_Application (Context : in Faces_Context) return Application_Access; -- Get the current lifecycle phase. function Get_Current_Phase (Context : in Faces_Context) return ASF.Events.Phases.Phase_Type; -- Set the current lifecycle phase. This operation is called by the lifecycle manager -- each time the lifecycle phase changes. procedure Set_Current_Phase (Context : in out Faces_Context; Phase : in ASF.Events.Phases.Phase_Type); -- Get the locale defined by the view root component. -- Returns the NULL_LOCALE if there is no view root component. function Get_Locale (Context : in Faces_Context) return Util.Locales.Locale; -- Set the locale that must be used when rendering the view components. procedure Set_Locale (Context : in out Faces_Context; Locale : in Util.Locales.Locale); -- Get the component view root. function Get_View_Root (Context : in Faces_Context) return ASF.Components.Root.UIViewRoot; -- Get the component view root. procedure Set_View_Root (Context : in out Faces_Context; View : in ASF.Components.Root.UIViewRoot); -- Create an identifier for a component. procedure Create_Unique_Id (Context : in out Faces_Context; Id : out Natural); -- Set the exception handler that will receive unexpected exceptions and process them. procedure Set_Exception_Handler (Context : in out Faces_Context; Handler : in Exceptions.Exception_Handler_Access); -- Get the exception handler. function Get_Exception_Handler (Context : in Faces_Context) return Exceptions.Exception_Handler_Access; -- Queue an exception event to the exception handler associated with the context. -- The exception event will be processed at the end of the current ASF phase. procedure Queue_Exception (Context : in out Faces_Context; Ex : in Ada.Exceptions.Exception_Occurrence); -- Iterate over the exceptions that have been queued and execute the <b>Process</b> -- procedure. When the procedure returns True in <b>Remove</b, the exception event -- is removed from the queue. The procedure can update the faces context to add some -- error message or redirect to an error page. -- -- The application exception handler uses this procedure to process the exceptions. -- The exception handler is called after each ASF phase. procedure Iterate_Exception (Context : in out Faces_Context'Class; Process : not null access procedure (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out Faces_Context'Class)); -- Returns True if the current request is an AJAX request. function Is_Ajax_Request (Context : in Faces_Context'Class) return Boolean; -- Set the Ajax request status. procedure Set_Ajax_Request (Context : in out Faces_Context'Class; Status : in Boolean); -- Get the current faces context. The faces context is saved -- in a per-thread/task attribute. function Current return Faces_Context_Access; -- Set the current faces context in the per-thread/task attribute. procedure Set_Current (Context : in Faces_Context_Access; Application : in Application_Access); -- Restore the previous faces context. procedure Restore (Context : in Faces_Context_Access); private use ASF.Applications.Messages; type Exception_Queue_Access is access ASF.Contexts.Exceptions.Exception_Queue; -- Map of messages associated with a component package Message_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Vectors.Vector, Hash => Hash, Equivalent_Keys => "=", "=" => Vectors."="); type Faces_Context is new Ada.Finalization.Limited_Controlled with record -- The response writer. Writer : ASF.Contexts.Writer.Response_Writer_Access; -- The expression context; Context : EL.Contexts.ELContext_Access; -- The request Request : ASF.Requests.Request_Access; -- The response Response : ASF.Responses.Response_Access; -- The application Application : Application_Access; -- The exception handler and exception queue. Except_Handler : Exceptions.Exception_Handler_Access; Except_Queue : Exception_Queue_Access; Render_Response : Boolean := False; Response_Completed : Boolean := False; -- True if the view is processed as part of an AJAX request. Ajax : Boolean := False; -- List of messages added indexed by the client identifier. Messages : Message_Maps.Map; -- The maximum severity for the messages that were collected. Max_Severity : Severity := NONE; Root : ASF.Components.Root.UIViewRoot; -- The flash context. Flash : Flash_Context_Access; -- The current lifecycle phase. Phase : ASF.Events.Phases.Phase_Type := ASF.Events.Phases.RESTORE_VIEW; -- The locale defined by the view root component. Unlike JSF, we store the locale -- in the faces context. This is easier for the implementation. Locale : Util.Locales.Locale := Util.Locales.NULL_LOCALE; end record; -- Release any storage held by this context. overriding procedure Finalize (Context : in out Faces_Context); end ASF.Contexts.Faces;
----------------------------------------------------------------------- -- asf-contexts.faces -- Faces Contexts -- 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 ASF.Requests; with ASF.Responses; with ASF.Sessions; limited with ASF.Converters; with ASF.Components.Root; limited with ASF.Applications.Main; with ASF.Applications.Messages; with ASF.Applications.Messages.Vectors; with ASF.Contexts.Writer; with ASF.Contexts.Exceptions; limited with ASF.Contexts.Flash; with ASF.Events.Exceptions; with ASF.Events.Phases; with EL.Objects; with EL.Contexts; with Util.Locales; with Util.Beans.Basic; with Ada.Exceptions; with Ada.Strings.Unbounded; private with Ada.Finalization; private with Ada.Strings.Unbounded.Hash; private with Ada.Containers.Hashed_Maps; -- The <b>Faces_Context</b> is an object passed to the component tree and -- bean actions to provide the full context in which the view is rendered -- or evaluated. The faces context gives access to the bean variables, -- the request and its parameters, the response writer to write on the -- output stream. -- -- The <b>Faces_Context</b> is never shared: it is specific to each request. package ASF.Contexts.Faces is use Ada.Strings.Unbounded; type Application_Access is access all ASF.Applications.Main.Application'Class; type Flash_Context_Access is access all ASF.Contexts.Flash.Flash_Context'Class; type Faces_Context is tagged limited private; type Faces_Context_Access is access all Faces_Context'Class; -- Get the response writer to write the response stream. function Get_Response_Writer (Context : Faces_Context) return ASF.Contexts.Writer.Response_Writer_Access; -- Set the response writer to write to the response stream. procedure Set_Response_Writer (Context : in out Faces_Context; Writer : in ASF.Contexts.Writer.Response_Writer_Access); -- Get the EL context for evaluating expressions. function Get_ELContext (Context : in Faces_Context) return EL.Contexts.ELContext_Access; -- Set the EL context for evaluating expressions. procedure Set_ELContext (Context : in out Faces_Context; ELContext : in EL.Contexts.ELContext_Access); -- Set the attribute having given name with the value. procedure Set_Attribute (Context : in out Faces_Context; Name : in String; Value : in EL.Objects.Object); -- Set the attribute having given name with the value. procedure Set_Attribute (Context : in out Faces_Context; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the attribute with the given name. function Get_Attribute (Context : in Faces_Context; Name : in String) return EL.Objects.Object; -- Get the attribute with the given name. function Get_Attribute (Context : in Faces_Context; Name : in Unbounded_String) return EL.Objects.Object; -- Get the bean attribute with the given name. -- Returns null if the attribute does not exist or is not a bean. function Get_Bean (Context : in Faces_Context; Name : in String) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a request parameter function Get_Parameter (Context : Faces_Context; Name : String) return String; -- Get the session associated with the current faces context. function Get_Session (Context : in Faces_Context; Create : in Boolean := False) return ASF.Sessions.Session; -- Get the request function Get_Request (Context : Faces_Context) return ASF.Requests.Request_Access; -- Set the request procedure Set_Request (Context : in out Faces_Context; Request : in ASF.Requests.Request_Access); -- Get the response function Get_Response (Context : Faces_Context) return ASF.Responses.Response_Access; -- Set the response procedure Set_Response (Context : in out Faces_Context; Response : in ASF.Responses.Response_Access); -- Signal the JavaServer faces implementation that, as soon as the -- current phase of the request processing lifecycle has been completed, -- control should be passed to the <b>Render Response</b> phase, -- bypassing any phases that have not been executed yet. procedure Render_Response (Context : in out Faces_Context); -- Check whether the <b>Render_Response</b> phase must be processed immediately. function Get_Render_Response (Context : in Faces_Context) return Boolean; -- Signal the JavaServer Faces implementation that the HTTP response -- for this request has already been generated (such as an HTTP redirect), -- and that the request processing lifecycle should be terminated as soon -- as the current phase is completed. procedure Response_Completed (Context : in out Faces_Context); -- Check whether the response has been completed. function Get_Response_Completed (Context : in Faces_Context) return Boolean; -- Get the flash context allowing to add flash attributes. function Get_Flash (Context : in Faces_Context) return Flash_Context_Access; -- Set the flash context. procedure Set_Flash (Context : in out Faces_Context; Flash : in Flash_Context_Access); -- Append the message to the list of messages associated with the specified -- client identifier. If <b>Client_Id</b> is empty, the message is global -- (or not associated with a component) procedure Add_Message (Context : in out Faces_Context; Client_Id : in String; Message : in ASF.Applications.Messages.Message); -- Append the message to the list of messages associated with the specified -- client identifier. If <b>Client_Id</b> is empty, the message is global -- (or not associated with a component) procedure Add_Message (Context : in out Faces_Context; Client_Id : in String; Message : in String; Severity : in Applications.Messages.Severity := Applications.Messages.ERROR); -- Append the messages defined in <b>Messages</b> to the current list of messages -- in the faces context. procedure Add_Messages (Context : in out Faces_Context; Client_Id : in String; Messages : in ASF.Applications.Messages.Vectors.Vector); -- Get an iterator for the messages associated with the specified client -- identifier. If the <b>Client_Id</b> ie empty, an iterator for the -- global messages is returned. function Get_Messages (Context : in Faces_Context; Client_Id : in String) return ASF.Applications.Messages.Vectors.Cursor; -- Returns the maximum severity level recorded for any message that has been queued. -- Returns NONE if no message has been queued. function Get_Maximum_Severity (Context : in Faces_Context) return ASF.Applications.Messages.Severity; -- Get a converter from a name. -- Returns the converter object or null if there is no converter. function Get_Converter (Context : in Faces_Context; Name : in EL.Objects.Object) return access ASF.Converters.Converter'Class; -- Get the application associated with this faces context. function Get_Application (Context : in Faces_Context) return Application_Access; -- Get the current lifecycle phase. function Get_Current_Phase (Context : in Faces_Context) return ASF.Events.Phases.Phase_Type; -- Set the current lifecycle phase. This operation is called by the lifecycle manager -- each time the lifecycle phase changes. procedure Set_Current_Phase (Context : in out Faces_Context; Phase : in ASF.Events.Phases.Phase_Type); -- Get the locale defined by the view root component. -- Returns the NULL_LOCALE if there is no view root component. function Get_Locale (Context : in Faces_Context) return Util.Locales.Locale; -- Set the locale that must be used when rendering the view components. procedure Set_Locale (Context : in out Faces_Context; Locale : in Util.Locales.Locale); -- Get the component view root. function Get_View_Root (Context : in Faces_Context) return ASF.Components.Root.UIViewRoot; -- Get the component view root. procedure Set_View_Root (Context : in out Faces_Context; View : in ASF.Components.Root.UIViewRoot); -- Get the view name associated with the current faces request. -- The view name is obtained from the request and the route mapping definition. -- If a pretty URL configuration was set through the `url-mapping` definition, the view -- name correspond to the `view-id` declaration. Otherwise, the view name corresponds -- to the servlet's path. function Get_View_Name (Context : in Faces_Context) return String; -- Create an identifier for a component. procedure Create_Unique_Id (Context : in out Faces_Context; Id : out Natural); -- Set the exception handler that will receive unexpected exceptions and process them. procedure Set_Exception_Handler (Context : in out Faces_Context; Handler : in Exceptions.Exception_Handler_Access); -- Get the exception handler. function Get_Exception_Handler (Context : in Faces_Context) return Exceptions.Exception_Handler_Access; -- Queue an exception event to the exception handler associated with the context. -- The exception event will be processed at the end of the current ASF phase. procedure Queue_Exception (Context : in out Faces_Context; Ex : in Ada.Exceptions.Exception_Occurrence); -- Iterate over the exceptions that have been queued and execute the <b>Process</b> -- procedure. When the procedure returns True in <b>Remove</b, the exception event -- is removed from the queue. The procedure can update the faces context to add some -- error message or redirect to an error page. -- -- The application exception handler uses this procedure to process the exceptions. -- The exception handler is called after each ASF phase. procedure Iterate_Exception (Context : in out Faces_Context'Class; Process : not null access procedure (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out Faces_Context'Class)); -- Returns True if the current request is an AJAX request. function Is_Ajax_Request (Context : in Faces_Context'Class) return Boolean; -- Set the Ajax request status. procedure Set_Ajax_Request (Context : in out Faces_Context'Class; Status : in Boolean); -- Get the current faces context. The faces context is saved -- in a per-thread/task attribute. function Current return Faces_Context_Access; -- Set the current faces context in the per-thread/task attribute. procedure Set_Current (Context : in Faces_Context_Access; Application : in Application_Access); -- Restore the previous faces context. procedure Restore (Context : in Faces_Context_Access); private use ASF.Applications.Messages; type Exception_Queue_Access is access ASF.Contexts.Exceptions.Exception_Queue; -- Map of messages associated with a component package Message_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Vectors.Vector, Hash => Hash, Equivalent_Keys => "=", "=" => Vectors."="); type Faces_Context is new Ada.Finalization.Limited_Controlled with record -- The response writer. Writer : ASF.Contexts.Writer.Response_Writer_Access; -- The expression context; Context : EL.Contexts.ELContext_Access; -- The request Request : ASF.Requests.Request_Access; -- The response Response : ASF.Responses.Response_Access; -- The application Application : Application_Access; -- The exception handler and exception queue. Except_Handler : Exceptions.Exception_Handler_Access; Except_Queue : Exception_Queue_Access; Render_Response : Boolean := False; Response_Completed : Boolean := False; -- True if the view is processed as part of an AJAX request. Ajax : Boolean := False; -- List of messages added indexed by the client identifier. Messages : Message_Maps.Map; -- The maximum severity for the messages that were collected. Max_Severity : Severity := NONE; Root : ASF.Components.Root.UIViewRoot; -- The flash context. Flash : Flash_Context_Access; -- The current lifecycle phase. Phase : ASF.Events.Phases.Phase_Type := ASF.Events.Phases.RESTORE_VIEW; -- The locale defined by the view root component. Unlike JSF, we store the locale -- in the faces context. This is easier for the implementation. Locale : Util.Locales.Locale := Util.Locales.NULL_LOCALE; end record; -- Release any storage held by this context. overriding procedure Finalize (Context : in out Faces_Context); end ASF.Contexts.Faces;
Declare the Get_View_Name function to retrieve the request view name
Declare the Get_View_Name function to retrieve the request view name
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
147a1c5815cf97874589f7daf84741636e513d52
src/security-controllers.ads
src/security-controllers.ads
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; with Security.Permissions; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/ada-security
9fbb21d997dfaa9f3385096a4381634ae6977b72
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- ado-schemas-tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 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.Directories; with Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Parameters; with ADO.Schemas.Databases; with ADO.Sessions.Sources; with ADO.Sessions.Entities; with ADO.Schemas.Entities; with Regtests; with Regtests.Audits.Model; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T1 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Table => Regtests.Audits.Model.AUDIT_TABLE); T2 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Table => Regtests.Audits.Model.EMAIL_TABLE); T3 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Name => "audit_property"); begin T.Assert (T1 > 0, "T1 must be positive"); T.Assert (T2 > 0, "T2 must be positive"); T.Assert (T3 > 0, "T3 must be positive"); T.Assert (T4 > 0, "T4 must be positive"); T.Assert (T5 > 0, "T5 must be positive"); T.Assert (T1 /= T2, "Two distinct tables have different entity types (T1, T2)"); T.Assert (T2 /= T3, "Two distinct tables have different entity types (T2, T3)"); T.Assert (T3 /= T4, "Two distinct tables have different entity types (T3, T4)"); T.Assert (T4 /= T5, "Two distinct tables have different entity types (T4, T5)"); T.Assert (T5 /= T1, "Two distinct tables have different entity types (T5, T1)"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; declare P : ADO.Parameters.Parameter := ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0, Len => 0, Value_Len => 0, Position => 0, Name => ""); begin P := C.Expand ("something"); T.Assert (False, "Expand did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (Is_Primary (C), "Column must be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); T.Assert (not Is_Primary (C), "Column must not be a primary key"); Assert_Equals (T, 255, Get_Size (C), "Column has invalid size"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 21, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 10, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
----------------------------------------------------------------------- -- ado-schemas-tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 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.Directories; with Util.Test_Caller; with Util.Strings.Vectors; with Util.Strings.Transforms; with ADO.Parameters; with ADO.Schemas.Databases; with ADO.Sessions.Sources; with ADO.Sessions.Entities; with ADO.Schemas.Entities; with Regtests; with Regtests.Audits.Model; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; function To_Lower_Case (S : in String) return String renames Util.Strings.Transforms.To_Lower_Case; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database", Test_Create_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T1 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Table => Regtests.Audits.Model.AUDIT_TABLE); T2 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Table => Regtests.Audits.Model.EMAIL_TABLE); T3 : constant ADO.Entity_Type := Sessions.Entities.Find_Entity_Type (Session => S, Name => "audit_property"); begin T.Assert (T1 > 0, "T1 must be positive"); T.Assert (T2 > 0, "T2 must be positive"); T.Assert (T3 > 0, "T3 must be positive"); T.Assert (T4 > 0, "T4 must be positive"); T.Assert (T5 > 0, "T5 must be positive"); T.Assert (T1 /= T2, "Two distinct tables have different entity types (T1, T2)"); T.Assert (T2 /= T3, "Two distinct tables have different entity types (T2, T3)"); T.Assert (T3 /= T4, "Two distinct tables have different entity types (T3, T4)"); T.Assert (T4 /= T5, "Two distinct tables have different entity types (T4, T5)"); T.Assert (T5 /= T1, "Two distinct tables have different entity types (T5, T1)"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; declare P : ADO.Parameters.Parameter := ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0, Len => 0, Value_Len => 0, Position => 0, Name => ""); begin P := C.Expand ("something"); T.Assert (False, "Expand did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); T.Assert (Is_Primary (C), "Column must be a primary key"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); T.Assert (not Is_Primary (C), "Column must not be a primary key"); Assert_Equals (T, 255, Get_Size (C), "Column has invalid size"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 21, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 11, Count, "Invalid number of tables found in the schema"); elsif Driver = "postgresql" then Util.Tests.Assert_Equals (T, 11, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; -- ------------------------------ -- Test the creation of database. -- ------------------------------ procedure Test_Create_Schema (T : in out Test) is use ADO.Sessions.Sources; Msg : Util.Strings.Vectors.Vector; Cfg : Data_Source := Data_Source (Regtests.Get_Controller); Driver : constant String := Cfg.Get_Driver; Database : constant String := Cfg.Get_Database; Path : constant String := "db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql"; pragma Unreferenced (Msg); begin if Driver = "sqlite" then if Ada.Directories.Exists (Database & ".test") then Ada.Directories.Delete_File (Database & ".test"); end if; Cfg.Set_Database (Database & ".test"); ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); T.Assert (Ada.Directories.Exists (Database & ".test"), "The sqlite database was not created"); else ADO.Schemas.Databases.Create_Database (Admin => Cfg, Config => Cfg, Schema_Path => Path, Messages => Msg); end if; end Test_Create_Schema; end ADO.Schemas.Tests;
Update the unit test after introduction of a new test database table
Update the unit test after introduction of a new test database table
Ada
apache-2.0
stcarrez/ada-ado
7b8adea515885013c4a1a2785a991392aeea11a5
src/util-encoders.ads
src/util-encoders.ads
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Interfaces; -- === Encoder and Decoders === -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects -- which provide a mechanism to transform a stream from one format into -- another format. -- -- ==== Simple encoding and decoding ==== -- package Util.Encoders is pragma Preelaborate; Not_Supported : exception; Encoding_Error : exception; -- Encoder/decoder for Base64 (RFC 4648) BASE_64 : constant String := "base64"; -- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet -- (+ and / are replaced by - and _) BASE_64_URL : constant String := "base64url"; -- Encoder/decoder for Base16 (RFC 4648) BASE_16 : constant String := "base16"; HEX : constant String := "hex"; -- Encoder for SHA1 (RFC 3174) HASH_SHA1 : constant String := "sha1"; -- ------------------------------ -- Encoder context object -- ------------------------------ -- The <b>Encoder</b> provides operations to encode and decode -- strings or stream of data from one format to another. -- The <b>Encoded</b> contains two <b>Transformer</b> -- which either <i>encodes</i> or <i>decodes</i> the stream. type Encoder is tagged limited private; -- 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; function Encode_Binary (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String; -- Create the encoder object for the specified encoding format. function Create (Name : in String) return Encoder; type Decoder is tagged limited private; -- 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; function Decode_Binary (E : in Decoder; Data : in String) return Ada.Streams.Stream_Element_Array; -- Create the decoder object for the specified encoding format. function Create (Name : in String) return Decoder; -- ------------------------------ -- Stream Transformation interface -- ------------------------------ -- The <b>Transformer</b> interface defines the operation to transform -- a stream from one data format to another. type Transformer is limited interface; type Transformer_Access is access all Transformer'Class; -- Transform the input array represented by <b>Data</b> into -- the output array <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, encryption, compression, ...). -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> array. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output array <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- array cannot be transformed. procedure Transform (E : in out Transformer; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is abstract; -- Finish encoding the input array. procedure Finish (E : in out Transformer; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is null; -- 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; -- 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 Ada.Streams.Stream_Element_Array) return String; function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return Ada.Streams.Stream_Element_Array; -- 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); -- 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); -- 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); private type Encoder is new Ada.Finalization.Limited_Controlled with record Encode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); type Decoder is new Ada.Finalization.Limited_Controlled with record Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Decoder); end Util.Encoders;
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Interfaces; -- === Encoder and Decoders === -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects -- which provide a mechanism to transform a stream from one format into -- another format. -- -- ==== Simple encoding and decoding ==== -- package Util.Encoders is pragma Preelaborate; Not_Supported : exception; Encoding_Error : exception; -- Encoder/decoder for Base64 (RFC 4648) BASE_64 : constant String := "base64"; -- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet -- (+ and / are replaced by - and _) BASE_64_URL : constant String := "base64url"; -- Encoder/decoder for Base16 (RFC 4648) BASE_16 : constant String := "base16"; HEX : constant String := "hex"; -- Encoder for SHA1 (RFC 3174) HASH_SHA1 : constant String := "sha1"; -- ------------------------------ -- Encoder context object -- ------------------------------ -- The <b>Encoder</b> provides operations to encode and decode -- strings or stream of data from one format to another. -- The <b>Encoded</b> contains two <b>Transformer</b> -- which either <i>encodes</i> or <i>decodes</i> the stream. type Encoder is tagged limited private; -- 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; function Encode_Binary (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String; -- Create the encoder object for the specified encoding format. function Create (Name : in String) return Encoder; type Decoder is tagged limited private; -- 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; function Decode_Binary (E : in Decoder; Data : in String) return Ada.Streams.Stream_Element_Array; -- Create the decoder object for the specified encoding format. function Create (Name : in String) return Decoder; -- ------------------------------ -- Stream Transformation interface -- ------------------------------ -- The <b>Transformer</b> interface defines the operation to transform -- a stream from one data format to another. type Transformer is limited interface; type Transformer_Access is access all Transformer'Class; -- Transform the input array represented by <b>Data</b> into -- the output array <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, encryption, compression, ...). -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> array. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output array <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- array cannot be transformed. procedure Transform (E : in out Transformer; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is abstract; -- Finish encoding the input array. procedure Finish (E : in out Transformer; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is null; -- 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; -- 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 Ada.Streams.Stream_Element_Array) return String; function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return Ada.Streams.Stream_Element_Array; -- 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); -- 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); -- 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); private -- Transform the input data into the target string. procedure Convert (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array; Into : out String); type Encoder is new Ada.Finalization.Limited_Controlled with record Encode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); type Decoder is new Ada.Finalization.Limited_Controlled with record Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Decoder); end Util.Encoders;
Declare a Convert internal procedure to make a transformation and get the final result in a string passed as parameter. This function is intended to be used for Base16 and Base64 encoding for HMAC/SHA operations where the target string size is well known.
Declare a Convert internal procedure to make a transformation and get the final result in a string passed as parameter. This function is intended to be used for Base16 and Base64 encoding for HMAC/SHA operations where the target string size is well known.
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2902428f54050a9b253e5f7a5886897fce56afa7
src/security-contexts.adb
src/security-contexts.adb
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- 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.Task_Attributes; with Security.Controllers; package body Security.Contexts is package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Permissions.Permission_Manager_Access is begin return Context.Manager; end 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) is use type Security.Permissions.Controller_Access; use type Security.Permissions.Permission_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare C : constant Permissions.Controller_Access := Context.Manager.Get_Controller (Permission); begin if C = null then Result := False; else -- Result := C.Has_Permission (Context); Result := False; end if; end; end Has_Permission; -- ------------------------------ -- 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) is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin Security_Context'Class (Context).Has_Permission (Index, Result); end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is begin Task_Context.Set_Value (Context.Previous); end Finalize; -- ------------------------------ -- 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) is begin Context.Context.Include (Key => Name, New_Item => Value); end Add_Context; -- ------------------------------ -- 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 is Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else raise Invalid_Context; end if; end Get_Context; -- ------------------------------ -- 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 is use type Util.Strings.Maps.Cursor; begin return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element; end Has_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) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; -- ------------------------------ -- 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 is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; 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.Task_Attributes; with Security.Controllers; package body Security.Contexts is package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- 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) is use type Security.Policies.Controller_Access; use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare C : constant Policies.Controller_Access := Context.Manager.Get_Controller (Permission); begin if C = null then Result := False; else -- Result := C.Has_Permission (Context); Result := False; end if; end; end Has_Permission; -- ------------------------------ -- 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) is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin Security_Context'Class (Context).Has_Permission (Index, Result); end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is begin Task_Context.Set_Value (Context.Previous); end Finalize; -- ------------------------------ -- 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) is begin Context.Context.Include (Key => Name, New_Item => Value); end Add_Context; -- ------------------------------ -- 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 is Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else raise Invalid_Context; end if; end Get_Context; -- ------------------------------ -- 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 is use type Util.Strings.Maps.Cursor; begin return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element; end Has_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; -- ------------------------------ -- 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 is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; end Security.Contexts;
Use the policy manager
Use the policy manager
Ada
apache-2.0
Letractively/ada-security
47492ae6cd55c5e23efa6238bf23a63e0dbba31b
src/wiki-render-text.ads
src/wiki-render-text.ads
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams; -- == Text Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Text is -- ------------------------------ -- Wiki to Text renderer -- ------------------------------ type Text_Renderer is new Wiki.Render.Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a line break (<br>). procedure Add_Line_Break (Document : in out Text_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Text_Renderer; Level : in Natural); -- 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 Text_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Text_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String); -- Add a text block with the given format. procedure Add_Text (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Wiki.Documents.Format_Map); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Start_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Text_Renderer); private -- Emit a new line. procedure New_Line (Document : in out Text_Renderer); procedure Close_Paragraph (Document : in out Text_Renderer); procedure Open_Paragraph (Document : in out Text_Renderer); type Text_Renderer is new Wiki.Render.Renderer with record Output : Streams.Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 0; end record; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Streams; -- == Text Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Text is -- ------------------------------ -- Wiki to Text renderer -- ------------------------------ type Text_Renderer is new Wiki.Render.Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a line break (<br>). procedure Add_Line_Break (Document : in out Text_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Text_Renderer; Level : in Natural); -- 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 Text_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String); -- Add an image. procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String); -- Add a quote. procedure Add_Quote (Document : in out Text_Renderer; 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 Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Start_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Text_Renderer); private -- Emit a new line. procedure New_Line (Document : in out Text_Renderer); procedure Close_Paragraph (Document : in out Text_Renderer); procedure Open_Paragraph (Document : in out Text_Renderer); type Text_Renderer is new Wiki.Render.Renderer with record Output : Streams.Output_Stream_Access := null; Format : Wiki.Documents.Format_Map := (others => False); Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Indent_Level : Natural := 0; end record; end Wiki.Render.Text;
Remove the Add_Text procedure
Remove the Add_Text procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b201dfa135860a41673f4ea0a1c413c30beac958
samples/bean.adb
samples/bean.adb
----------------------------------------------------------------------- -- bean - A simple bean example -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Beans.Factory; with EL.Beans.Methods.Func_String; with EL.Beans.Methods.Func_Unbounded; with Ada.Unchecked_Deallocation; package body Bean is use EL.Objects; use EL.Beans.Methods; FIRST_NAME : constant String := "firstName"; LAST_NAME : constant String := "lastName"; AGE : constant String := "age"; Null_Object : Object; function Create_Person (First_Name, Last_Name : String; Age : Natural) return Person_Access is begin return new Person '(First_Name => To_Unbounded_String (First_Name), Last_Name => To_Unbounded_String (Last_Name), Age => Age); end Create_Person; -- Get the value identified by the name. function Get_Value (From : Person; Name : String) return EL.Objects.Object is begin if Name = FIRST_NAME then return To_Object (From.First_Name); elsif Name = LAST_NAME then return To_Object (From.Last_Name); elsif Name = AGE then return To_Object (From.Age); else return Null_Object; end if; end Get_Value; -- Set the value identified by the name. procedure Set_Value (From : in out Person; Name : in String; Value : in EL.Objects.Object) is begin if Name = FIRST_NAME then From.First_Name := To_Unbounded_String (Value); elsif Name = LAST_NAME then From.Last_Name := To_Unbounded_String (Value); elsif Name = AGE then From.Age := Natural (To_Integer (Value)); end if; end Set_Value; -- function Save (P : in Person; Name : in Unbounded_String) return Unbounded_String is Result : Unbounded_String; begin Result := P.Last_Name & Name; return Result; end Save; function Compute (B : EL.Beans.Bean'Class; P1 : EL.Objects.Object) return EL.Objects.Object is P : Person := Person (B); begin return P1; end Compute; -- Function to format a string function Format (Arg : EL.Objects.Object) return EL.Objects.Object is S : constant String := To_String (Arg); begin return To_Object ("[" & S & "]"); end Format; function Print (P : in Person; Title : in String) return String is begin return Title & " [" & "Name=" & To_String (P.First_Name) & ", " & "Last_name=" & To_String (P.Last_Name) & "]"; end Print; package Save_Binding is new Func_Unbounded.Bind (Bean => Person, Method => Save, Name => "save"); package Print_Binding is new Func_String.Bind (Bean => Person, Method => Print, Name => "print"); type Bean_Definition is new EL.Beans.Factory.Bean_Definition with null record; -- Create a bean. overriding function Create (Def : in Bean_Definition) return EL.Beans.Readonly_Bean_Access; -- Free the bean instance. overriding procedure Destroy (Def : in Bean_Definition; Bean : in out EL.Beans.Readonly_Bean_Access); -- Create a bean. overriding function Create (Def : in Bean_Definition) return EL.Beans.Readonly_Bean_Access is Result : Person_Access := new Person; begin return Result.all'Access; end Create; -- Free the bean instance. overriding procedure Destroy (Def : in Bean_Definition; Bean : in out EL.Beans.Readonly_Bean_Access) is begin null; end Destroy; B : aliased Bean_Definition := Bean_Definition '(Method_Count => 2, Methods => (Save_Binding.Proxy'Access, null) ); Binding_Array : aliased constant EL.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Print_Binding.Proxy'Access); function Get_Method_Bindings (From : in Person) return EL.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Unchecked_Access; end Get_Method_Bindings; procedure Free (Object : in out Person_Access) is procedure Free is new Ada.Unchecked_Deallocation (Object => Person'Class, Name => Person_Access); begin Free (Object); end Free; end Bean;
----------------------------------------------------------------------- -- bean - A simple bean example -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Beans.Factory; with EL.Beans.Methods.Func_String; with EL.Beans.Methods.Func_Unbounded; with Ada.Unchecked_Deallocation; package body Bean is use EL.Objects; use EL.Beans.Methods; FIRST_NAME : constant String := "firstName"; LAST_NAME : constant String := "lastName"; AGE : constant String := "age"; Null_Object : Object; function Create_Person (First_Name, Last_Name : String; Age : Natural) return Person_Access is begin return new Person '(First_Name => To_Unbounded_String (First_Name), Last_Name => To_Unbounded_String (Last_Name), Age => Age); end Create_Person; -- Get the value identified by the name. function Get_Value (From : Person; Name : String) return EL.Objects.Object is begin if Name = FIRST_NAME then return To_Object (From.First_Name); elsif Name = LAST_NAME then return To_Object (From.Last_Name); elsif Name = AGE then return To_Object (From.Age); else return Null_Object; end if; end Get_Value; -- Set the value identified by the name. procedure Set_Value (From : in out Person; Name : in String; Value : in EL.Objects.Object) is begin if Name = FIRST_NAME then From.First_Name := To_Unbounded_String (Value); elsif Name = LAST_NAME then From.Last_Name := To_Unbounded_String (Value); elsif Name = AGE then From.Age := Natural (To_Integer (Value)); end if; end Set_Value; -- function Save (P : in Person; Name : in Unbounded_String) return Unbounded_String is Result : Unbounded_String; begin Result := P.Last_Name & Name; return Result; end Save; function Compute (B : EL.Beans.Bean'Class; P1 : EL.Objects.Object) return EL.Objects.Object is P : Person := Person (B); begin return P1; end Compute; -- Function to format a string function Format (Arg : EL.Objects.Object) return EL.Objects.Object is S : constant String := To_String (Arg); begin return To_Object ("[" & S & "]"); end Format; function Print (P : in Person; Title : in String) return String is begin return Title & " [" & "Name=" & To_String (P.First_Name) & ", " & "Last_name=" & To_String (P.Last_Name) & "]"; end Print; package Save_Binding is new Func_Unbounded.Bind (Bean => Person, Method => Save, Name => "save"); package Print_Binding is new Func_String.Bind (Bean => Person, Method => Print, Name => "print"); type Bean_Definition is new EL.Beans.Factory.Bean_Definition with null record; -- Create a bean. overriding function Create (Def : in Bean_Definition) return EL.Beans.Readonly_Bean_Access; -- Free the bean instance. overriding procedure Destroy (Def : in Bean_Definition; Bean : in out EL.Beans.Readonly_Bean_Access); -- Create a bean. overriding function Create (Def : in Bean_Definition) return EL.Beans.Readonly_Bean_Access is Result : Person_Access := new Person; begin return Result.all'Access; end Create; -- Free the bean instance. overriding procedure Destroy (Def : in Bean_Definition; Bean : in out EL.Beans.Readonly_Bean_Access) is begin null; end Destroy; B : aliased Bean_Definition := Bean_Definition '(Method_Count => 2, Methods => (Save_Binding.Proxy'Access, null) ); Binding_Array : aliased constant EL.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Print_Binding.Proxy'Access); function Get_Method_Bindings (From : in Person) return EL.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; procedure Free (Object : in out Person_Access) is procedure Free is new Ada.Unchecked_Deallocation (Object => Person'Class, Name => Person_Access); begin Free (Object); end Free; end Bean;
Use an Access type
Use an Access type
Ada
apache-2.0
stcarrez/ada-el
0a860cfdd3a6ced8a064bff1de94d6b7769be10c
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.Processes; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings; with ASF.Events.Faces.Actions; with ASF.Contexts.Faces; with ASF.Applications.Main.Configs; with ASF.Applications.Messages.Factory; with AWA.Applications; package body AWA.Setup.Applications is use ASF.Applications; 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 From.Db_Host; elsif Name = "database_port" then return From.Db_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 From.Driver; elsif Name = "database_root_user" then return From.Root_User; elsif Name = "database_root_password" then return From.Root_Passwd; elsif Name = "result" then return From.Result; 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.Db_Host := Value; elsif Name = "database_port" then From.Db_Port := 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 = "database_driver" then From.Driver := Value; elsif Name = "database_root_user" then From.Root_User := Value; elsif Name = "database_root_password" then From.Root_Passwd := 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; Driver : constant String := Util.Beans.Objects.To_String (From.Driver); User : constant String := From.Database.Get_Property ("user"); begin if Driver = "" then Append (Result, "mysql"); else Append (Result, Driver); end if; Append (Result, "://"); if Driver /= "sqlite" then 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; end if; Append (Result, "/"); Append (Result, From.Database.Get_Database); if User /= "" then Append (Result, "?user="); Append (Result, User); if From.Database.Get_Property ("password") /= "" then Append (Result, "&password="); Append (Result, From.Database.Get_Property ("password")); end if; end if; if Driver = "sqlite" then if User /= "" then Append (Result, "&"); else Append (Result, "?"); end if; Append (Result, "synchronous=OFF&encoding=UTF-8"); end if; return To_String (Result); end Get_Database_URL; -- ------------------------------ -- Get the command to configure the database. -- ------------------------------ function Get_Configure_Command (From : in Application) return String is Driver : constant String := Util.Beans.Objects.To_String (From.Driver); Database : constant String := From.Get_Database_URL; Command : constant String := "dynamo create-database db '" & Database & "'"; Root : constant String := Util.Beans.Objects.To_String (From.Root_User); Passwd : constant String := Util.Beans.Objects.To_String (From.Root_Passwd); begin if Root = "" then return Command; elsif Passwd = "" then return Command & " " & Root; else return Command & " " & Root & " " & Passwd; end if; end Get_Configure_Command; -- ------------------------------ -- Validate the database configuration parameters. -- ------------------------------ procedure Validate (From : in out Application) is Driver : constant String := Util.Beans.Objects.To_String (From.Driver); begin From.Has_Error := False; if Driver = "sqlite" then return; end if; begin From.Database.Set_Port (Util.Beans.Objects.To_Integer (From.Db_Port)); exception when others => From.Has_Error := True; Messages.Factory.Add_Field_Message ("db-port", "setup.setup_database_port_error", Messages.ERROR); end; begin From.Database.Set_Server (Util.Beans.Objects.To_String (From.Db_Host)); exception when others => From.Has_Error := True; Messages.Factory.Add_Field_Message ("db-server", "setup.setup_database_host_error", Messages.ERROR); end; end Validate; -- ------------------------------ -- Configure the database. -- ------------------------------ procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin From.Validate; if From.Has_Error then Ada.Strings.Unbounded.Set_Unbounded_String (Outcome, "failure"); return; end if; declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Command : constant String := From.Get_Configure_Command; begin Log.Info ("Configure database with {0}", Command); Pipe.Open (Command, Util.Processes.READ); Buffer.Initialize (null, Pipe'Unchecked_Access, 64*1024); Buffer.Read (Content); Pipe.Close; From.Result := Util.Beans.Objects.To_Object (Content); From.Has_Error := Pipe.Get_Exit_Status /= 0; if From.Has_Error then Messages.Factory.Add_Message ("setup.database_setup_error", Messages.ERROR); end if; end; 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; Changed : ASF.Applications.Config := From.Changed; procedure Read_Property (Line : in String) is Pos : constant Natural := Util.Strings.Index (Line, '='); begin if Pos = 0 or else not 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, Changed.Get (Line (Line'First .. Pos - 1))); Changed.Remove (Line (Line'First .. Pos - 1)); end Read_Property; procedure Save_Property (Name : in Ada.Strings.Unbounded.Unbounded_String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Ada.Text_IO.Put (Output, Ada.Strings.Unbounded.To_String (Name)); Ada.Text_IO.Put (Output, "="); Ada.Text_IO.Put_Line (Output, Ada.Strings.Unbounded.To_String (Value)); end Save_Property; begin Log.Info ("Saving configuration file {0}", Path); Changed.Set ("database", From.Get_Database_URL); Ada.Text_IO.Create (File => Output, Name => New_File); Util.Files.Read_File (Path, Read_Property'Access); Changed.Iterate (Save_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"); App.Add_Mapping (Pattern => "*.png", 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 : constant Natural := Util.Strings.Index (URL, '#'); begin if Pos > 0 then App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1)); else App.Changed.Set ("callback_url", "http://mydomain.com/oauth"); end if; end; App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db")); App.Driver := Util.Beans.Objects.To_Object (App.Database.Get_Driver); if App.Database.Get_Driver = "mysql" then App.Db_Host := Util.Beans.Objects.To_Object (App.Database.Get_Server); App.Db_Port := Util.Beans.Objects.To_Object (App.Database.Get_Port); else App.Db_Host := Util.Beans.Objects.To_Object (String '("localhost")); App.Db_Port := Util.Beans.Objects.To_Object (Integer (3306)); end if; 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.Processes; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Strings; with ASF.Events.Faces.Actions; with ASF.Applications.Main.Configs; with ASF.Applications.Messages.Factory; with AWA.Applications; package body AWA.Setup.Applications is use ASF.Applications; 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 pragma Unreferenced (Server); 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 From.Db_Host; elsif Name = "database_port" then return From.Db_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 From.Driver; elsif Name = "database_root_user" then return From.Root_User; elsif Name = "database_root_password" then return From.Root_Passwd; elsif Name = "result" then return From.Result; 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.Db_Host := Value; elsif Name = "database_port" then From.Db_Port := 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 = "database_driver" then From.Driver := Value; elsif Name = "database_root_user" then From.Root_User := Value; elsif Name = "database_root_password" then From.Root_Passwd := 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; Driver : constant String := Util.Beans.Objects.To_String (From.Driver); User : constant String := From.Database.Get_Property ("user"); begin if Driver = "" then Append (Result, "mysql"); else Append (Result, Driver); end if; Append (Result, "://"); if Driver /= "sqlite" then 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; end if; Append (Result, "/"); Append (Result, From.Database.Get_Database); if User /= "" then Append (Result, "?user="); Append (Result, User); if From.Database.Get_Property ("password") /= "" then Append (Result, "&password="); Append (Result, From.Database.Get_Property ("password")); end if; end if; if Driver = "sqlite" then if User /= "" then Append (Result, "&"); else Append (Result, "?"); end if; Append (Result, "synchronous=OFF&encoding=UTF-8"); end if; return To_String (Result); end Get_Database_URL; -- ------------------------------ -- Get the command to configure the database. -- ------------------------------ function Get_Configure_Command (From : in Application) return String is Database : constant String := From.Get_Database_URL; Command : constant String := "dynamo create-database db '" & Database & "'"; Root : constant String := Util.Beans.Objects.To_String (From.Root_User); Passwd : constant String := Util.Beans.Objects.To_String (From.Root_Passwd); begin if Root = "" then return Command; elsif Passwd = "" then return Command & " " & Root; else return Command & " " & Root & " " & Passwd; end if; end Get_Configure_Command; -- ------------------------------ -- Validate the database configuration parameters. -- ------------------------------ procedure Validate (From : in out Application) is Driver : constant String := Util.Beans.Objects.To_String (From.Driver); Server : constant String := Util.Beans.Objects.To_String (From.Db_Host); begin From.Has_Error := False; if Driver = "sqlite" then return; end if; begin From.Database.Set_Port (Util.Beans.Objects.To_Integer (From.Db_Port)); exception when others => From.Has_Error := True; Messages.Factory.Add_Field_Message ("db-port", "setup.setup_database_port_error", Messages.ERROR); end; if Server'Length = 0 then From.Has_Error := True; Messages.Factory.Add_Field_Message ("db-server", "setup.setup_database_host_error", Messages.ERROR); end if; From.Database.Set_Server (Server); end Validate; -- ------------------------------ -- Configure the database. -- ------------------------------ procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin From.Validate; if not From.Has_Error then declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Command : constant String := From.Get_Configure_Command; begin Log.Info ("Configure database with {0}", Command); Pipe.Open (Command, Util.Processes.READ); Buffer.Initialize (null, Pipe'Unchecked_Access, 64 * 1024); Buffer.Read (Content); Pipe.Close; From.Result := Util.Beans.Objects.To_Object (Content); From.Has_Error := Pipe.Get_Exit_Status /= 0; if From.Has_Error then Messages.Factory.Add_Message ("setup.database_setup_error", Messages.ERROR); end if; end; end if; if From.Has_Error then Ada.Strings.Unbounded.Set_Unbounded_String (Outcome, "failure"); end if; end Configure_Database; -- ------------------------------ -- Save the configuration. -- ------------------------------ procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); procedure Save_Property (Name : in Ada.Strings.Unbounded.Unbounded_String; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Read_Property (Line : in String); Path : constant String := Ada.Strings.Unbounded.To_String (From.Path); New_File : constant String := Path & ".tmp"; Output : Ada.Text_IO.File_Type; Changed : ASF.Applications.Config := From.Changed; procedure Read_Property (Line : in String) is Pos : constant Natural := Util.Strings.Index (Line, '='); begin if Pos = 0 or else not 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, Changed.Get (Line (Line'First .. Pos - 1))); Changed.Remove (Line (Line'First .. Pos - 1)); end Read_Property; procedure Save_Property (Name : in Ada.Strings.Unbounded.Unbounded_String; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Ada.Text_IO.Put (Output, Ada.Strings.Unbounded.To_String (Name)); Ada.Text_IO.Put (Output, "="); Ada.Text_IO.Put_Line (Output, Ada.Strings.Unbounded.To_String (Value)); end Save_Property; begin Log.Info ("Saving configuration file {0}", Path); Changed.Set ("database", From.Get_Database_URL); Ada.Text_IO.Create (File => Output, Name => New_File); Util.Files.Read_File (Path, Read_Property'Access); Changed.Iterate (Save_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 pragma Unreferenced (Outcome); 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 pragma Unreferenced (From); 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"); App.Add_Mapping (Pattern => "*.png", 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 : constant Natural := Util.Strings.Index (URL, '#'); begin if Pos > 0 then App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1)); else App.Changed.Set ("callback_url", "http://mydomain.com/oauth"); end if; end; App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db")); App.Driver := Util.Beans.Objects.To_Object (App.Database.Get_Driver); if App.Database.Get_Driver = "mysql" then App.Db_Host := Util.Beans.Objects.To_Object (App.Database.Get_Server); App.Db_Port := Util.Beans.Objects.To_Object (App.Database.Get_Port); else App.Db_Host := Util.Beans.Objects.To_Object (String '("localhost")); App.Db_Port := Util.Beans.Objects.To_Object (Integer (3306)); end if; 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;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0315e6764d33f5f1f3942b4426d68e487f44a733
mat/src/mat-targets-readers.ads
mat/src/mat-targets-readers.ads
----------------------------------------------------------------------- -- 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 MAT.Events; with MAT.Readers; package MAT.Targets.Readers is type Process_Servant is new MAT.Readers.Reader_Base with record Target : Target_Type_Access; Reader : MAT.Readers.Manager; Process : Target_Process_Type_Access; end record; type Process_Reader_Access is access all Process_Servant'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); 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); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access); -- 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); private procedure Probe_Begin (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message); 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 MAT.Events; with MAT.Readers; package MAT.Targets.Readers is type Process_Servant is new MAT.Readers.Reader_Base with record Target : Target_Type_Access; Reader : MAT.Readers.Manager; Process : Target_Process_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Reader_Access is access all Process_Servant'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (For_Servant : in out Process_Servant; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); 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); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Process_Reader_Access); -- 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); private procedure Probe_Begin (For_Servant : in out Process_Servant; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message); end MAT.Targets.Readers;
Add the target events in the Process_Servant record
Add the target events in the Process_Servant record
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
57262fd3024e4f51ffe9c1a62a9945da9bfd81ed
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "2"; synth_version_minor : constant String := "05"; copyright_years : constant String := "2015-2018"; host_localbase : constant String := "/usr/local"; host_make : constant String := "/usr/bin/make"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; host_bmake : constant String := host_localbase & "/bin/bmake"; host_make_program : constant String := host_make; chroot_make : constant String := "/usr/bin/make"; chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk"; chroot_make_program : constant String := chroot_make; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type package_system is (ports_collection, pkgsrc); software_framework : constant package_system := ports_collection; -- Notes for tailoring Synth. Use sed to: -- 1. Modify host_localbase to value of LOCALBASE -- 2. Change software_framework to "pkgsrc" for pkgsrc version -- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms -- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version -- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "2"; synth_version_minor : constant String := "06"; copyright_years : constant String := "2015-2018"; host_localbase : constant String := "/usr/local"; host_make : constant String := "/usr/bin/make"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; host_bmake : constant String := host_localbase & "/bin/bmake"; host_make_program : constant String := host_make; chroot_make : constant String := "/usr/bin/make"; chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk"; chroot_make_program : constant String := chroot_make; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type package_system is (ports_collection, pkgsrc); software_framework : constant package_system := ports_collection; -- Notes for tailoring Synth. Use sed to: -- 1. Modify host_localbase to value of LOCALBASE -- 2. Change software_framework to "pkgsrc" for pkgsrc version -- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms -- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version -- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc end Definitions;
Bump version in preparation for release
Bump version in preparation for release
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
493a01692c1958fe081980d89f6142a1c10fb8f2
src/asf-components-widgets-panels.adb
src/asf-components-widgets-panels.adb
----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; package body ASF.Components.Widgets.Panels is -- ------------------------------ -- Render the panel header. -- ------------------------------ procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Header : Util.Beans.Objects.Object; Header_Facet : ASF.Components.Base.UIComponent_Access; begin Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-header"); Header := UI.Get_Attribute (Name => HEADER_ATTR_NAME, Context => Context); if not Util.Beans.Objects.Is_Empty (Header) then Writer.Start_Element ("span"); Writer.Write_Text (Header); Writer.End_Element ("span"); Writer.End_Element ("div"); end if; -- If there is a header facet, render it now. Header_Facet := UI.Get_Facet (HEADER_FACET_NAME); if Header_Facet /= null then Header_Facet.Encode_All (Context); end if; Writer.End_Element ("div"); null; end Render_Header; -- ------------------------------ -- Render the panel footer. -- ------------------------------ procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Footer : Util.Beans.Objects.Object; Footer_Facet : ASF.Components.Base.UIComponent_Access; Has_Footer : Boolean; begin Footer_Facet := UI.Get_Facet (FOOTER_FACET_NAME); Footer := UI.Get_Attribute (Name => FOOTER_ATTR_NAME, Context => Context); Has_Footer := Footer_Facet /= null or else not Util.Beans.Objects.Is_Empty (Footer); if Has_Footer then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-footer"); end if; if not Util.Beans.Objects.Is_Empty (Footer) then Writer.Write_Text (Footer); end if; -- If there is a footer facet, render it now. if Footer_Facet /= null then Footer_Facet.Encode_All (Context); end if; if Has_Footer then Writer.End_Element ("div"); end if; end Render_Footer; -- ------------------------------ -- Render the panel header and prepare for the panel content. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel"); UIPanel'Class (UI).Render_Header (Writer.all, Context); Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-content"); end if; end Encode_Begin; -- ------------------------------ -- Render the panel footer. -- ------------------------------ overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); UIPanel'Class (UI).Render_Footer (Writer.all, Context); Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Panels;
----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; package body ASF.Components.Widgets.Panels is -- ------------------------------ -- Render the panel header. -- ------------------------------ procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Header : Util.Beans.Objects.Object; Header_Facet : ASF.Components.Base.UIComponent_Access; begin Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-header ui-widget-header"); Header := UI.Get_Attribute (Name => HEADER_ATTR_NAME, Context => Context); if not Util.Beans.Objects.Is_Empty (Header) then Writer.Start_Element ("span"); Writer.Write_Text (Header); Writer.End_Element ("span"); Writer.End_Element ("div"); end if; -- If there is a header facet, render it now. Header_Facet := UI.Get_Facet (HEADER_FACET_NAME); if Header_Facet /= null then Header_Facet.Encode_All (Context); end if; Writer.End_Element ("div"); null; end Render_Header; -- ------------------------------ -- Render the panel footer. -- ------------------------------ procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Footer : Util.Beans.Objects.Object; Footer_Facet : ASF.Components.Base.UIComponent_Access; Has_Footer : Boolean; begin Footer_Facet := UI.Get_Facet (FOOTER_FACET_NAME); Footer := UI.Get_Attribute (Name => FOOTER_ATTR_NAME, Context => Context); Has_Footer := Footer_Facet /= null or else not Util.Beans.Objects.Is_Empty (Footer); if Has_Footer then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-footer ui-widget-footer"); end if; if not Util.Beans.Objects.Is_Empty (Footer) then Writer.Write_Text (Footer); end if; -- If there is a footer facet, render it now. if Footer_Facet /= null then Footer_Facet.Encode_All (Context); end if; if Has_Footer then Writer.End_Element ("div"); end if; end Render_Footer; -- ------------------------------ -- Render the panel header and prepare for the panel content. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel ui-widget ui-corner-all"); UIPanel'Class (UI).Render_Header (Writer.all, Context); Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-content ui-widget-content"); end if; end Encode_Begin; -- ------------------------------ -- Render the panel footer. -- ------------------------------ overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); UIPanel'Class (UI).Render_Footer (Writer.all, Context); Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Panels;
Add some CSS from jQuery UI widgets
Add some CSS from jQuery UI widgets
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
ad4f6e3b92598a559f0d013f5af330d63c1962fa
mat/src/mat-consoles-text.adb
mat/src/mat-consoles-text.adb
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is use type Ada.Text_IO.Count; Pos : Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Pos := Pos + Ada.Text_IO.Count (Console.Sizes (Field)); if Pos > Value'Length then Ada.Text_IO.Set_Col (Pos - Value'Length); else Ada.Text_IO.Set_Col (Ada.Text_IO.Count (Console.Cols (Field))); Ada.Text_IO.Put (Value (Value'Last - Console.Sizes (Field) .. Value'Last)); return; end if; end if; Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is use type Ada.Text_IO.Count; Pos : Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Pos := Pos + Ada.Text_IO.Count (Console.Sizes (Field)); if Pos > Value'Length then Ada.Text_IO.Set_Col (Pos - Value'Length); else Ada.Text_IO.Set_Col (Ada.Text_IO.Count (Console.Cols (Field))); Ada.Text_IO.Put (Value (Value'Last - Console.Sizes (Field) .. Value'Last)); return; end if; end if; Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Console.Sizes (Field)) - Title'Length); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
Implement the Notice procedure
Implement the Notice procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c1780be1a73b395344e3acdbad2fb0b2c12a667a
src/wiki-strings.ads
src/wiki-strings.ads
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Wide_Wide_Maps; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Ada.Strings.Wide_Wide_Fixed; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; subtype WChar_Mapping is Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Mapping; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Output_BOM : in Boolean := False) return String renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; function Is_Alphanumeric (C : in WChar) return Boolean renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric; function Index (S : in WString; P : in WString; Going : in Ada.Strings.Direction := Ada.Strings.Forward; Mapping : in WChar_Mapping := Ada.Strings.Wide_Wide_Maps.Identity) return Natural renames Ada.Strings.Wide_Wide_Fixed.Index; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Hash; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Ada.Strings.Wide_Wide_Fixed; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; subtype WChar_Mapping is Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Mapping; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Output_BOM : in Boolean := False) return String renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode; function Hash (S : in WString) return Ada.Containers.Hash_Type renames Ada.Strings.Wide_Wide_Hash; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; function Is_Alphanumeric (C : in WChar) return Boolean renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric; function Index (S : in WString; P : in WString; Going : in Ada.Strings.Direction := Ada.Strings.Forward; Mapping : in WChar_Mapping := Ada.Strings.Wide_Wide_Maps.Identity) return Natural renames Ada.Strings.Wide_Wide_Fixed.Index; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
Declare the Hash function as rename of Wide_Wide_Hash
Declare the Hash function as rename of Wide_Wide_Hash
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
95c8d47c2072d94cc91fdfad380d7fcab98cc222
awa/plugins/awa-comments/src/awa-comments-modules.ads
awa/plugins/awa-comments/src/awa-comments-modules.ads
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Modules.Get; with AWA.Modules.Lifecycles; with AWA.Comments.Models; -- == Integration == -- The <tt>Comment_Module</tt> manages the comments associated with entities. It provides -- operations that are used by the comment beans to manage the comments. -- An instance of the <tt>Comment_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 -- Comment_Module : aliased AWA.Comments.Modules.Comment_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Comments.Modules.NAME, -- URI => "comments", -- Module => App.Comment_Module'Access); -- package AWA.Comments.Modules is NAME : constant String := "comments"; Not_Found : exception; -- The <tt>Comment_Lifecycle</tt> package allows to receive life cycle events related -- to the <tt>Comment</tt> object. package Comment_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Comments.Models.Comment_Ref'Class); type Comment_Module is new AWA.Modules.Module with null record; type Comment_Module_Access is access all Comment_Module'Class; overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Load the comment identified by the given identifier. procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier); -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); -- Update the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. procedure Update_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); -- Delete the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. procedure Delete_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); -- Set the publication status of the comment represented by <tt>Comment</tt> -- if the current user has the permission identified by <tt>Permission</tt>. procedure Publish_Comment (Model : in Comment_Module; Permission : in String; Id : in ADO.Identifier; Status : in AWA.Comments.Models.Status_Type; Comment : in out AWA.Comments.Models.Comment_Ref'Class); function Get_Comment_Module is new AWA.Modules.Get (Comment_Module, Comment_Module_Access, NAME); end AWA.Comments.Modules;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Modules.Get; with AWA.Modules.Lifecycles; with AWA.Comments.Models; -- == Integration == -- The <tt>Comment_Module</tt> manages the comments associated with entities. It provides -- operations that are used by the comment beans to manage the comments. -- An instance of the <tt>Comment_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 -- Comment_Module : aliased AWA.Comments.Modules.Comment_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Comments.Modules.NAME, -- URI => "comments", -- Module => App.Comment_Module'Access); -- package AWA.Comments.Modules is NAME : constant String := "comments"; Not_Found : exception; -- The <tt>Comment_Lifecycle</tt> package allows to receive life cycle events related -- to the <tt>Comment</tt> object. package Comment_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Comments.Models.Comment_Ref'Class); subtype Listener is Comment_Lifecycle.Listener; type Comment_Module is new AWA.Modules.Module with null record; type Comment_Module_Access is access all Comment_Module'Class; overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Load the comment identified by the given identifier. procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier); -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); -- Update the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. procedure Update_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); -- Delete the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. procedure Delete_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class); -- Set the publication status of the comment represented by <tt>Comment</tt> -- if the current user has the permission identified by <tt>Permission</tt>. procedure Publish_Comment (Model : in Comment_Module; Permission : in String; Id : in ADO.Identifier; Status : in AWA.Comments.Models.Status_Type; Comment : in out AWA.Comments.Models.Comment_Ref'Class); function Get_Comment_Module is new AWA.Modules.Get (Comment_Module, Comment_Module_Access, NAME); end AWA.Comments.Modules;
Define the subtype Listener
Define the subtype Listener
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e0977a4e2dda99bd9832466d58d1c6e1c92e4138
src/util-serialize-io-json.ads
src/util-serialize-io-json.ads
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Util.Streams.Texts; with Util.Stacks; with Util.Beans.Objects; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON 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); -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON 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 JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" 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 a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). 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 an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); 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); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Read a JSON file and return an object. function Read (Path : in String) return Util.Beans.Objects.Object; private type Node_Info is record Is_Array : Boolean := False; Is_Root : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; Stream : Util.Streams.Texts.Print_Stream_Access; end record; procedure Write_Field_Name (Stream : in out Output_Stream; Name : in String); type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Util.Streams.Texts; with Util.Stacks; with Util.Beans.Objects; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON 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); -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON 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 JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" 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 a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). 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 an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); 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.Input_Buffer_Stream'Class; Sink : in out Reader'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Read a JSON file and return an object. function Read (Path : in String) return Util.Beans.Objects.Object; private type Node_Info is record Is_Array : Boolean := False; Is_Root : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; Stream : Util.Streams.Texts.Print_Stream_Access; end record; procedure Write_Field_Name (Stream : in out Output_Stream; Name : in String); type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
Use the Input_Buffer_Stream instead of Buffered_Stream
Use the Input_Buffer_Stream instead of Buffered_Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a441fcae57bc5258cb5b94da5f58a369dc5b56e9
awt/src/awt-inputs-gamepads.ads
awt/src/awt-inputs-gamepads.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 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. private with Ada.Finalization; private with Ada.Strings.Unbounded; private with AWT.Gamepads; package AWT.Inputs.Gamepads with SPARK_Mode => On is pragma Preelaborate; type Connection_Kind is (Disconnected, Wired, Wireless); type GUID_String is new String (1 .. 32) with Dynamic_Predicate => (for all C of GUID_String => C in '0' .. '9' | 'a' .. 'f'); -- FIXME Support motion sensor type Normalized is new Float range 0.0 .. 1.0; ---------------------------------------------------------------------------- type Gamepad_Button is (Direction_Up, Direction_Right, Direction_Down, Direction_Left, Action_Down, Action_Right, Action_Left, Action_Up, Shoulder_Left, Shoulder_Right, Thumb_Left, Thumb_Right, Center_Left, Center_Right, Center_Logo); type Gamepad_Axis is (Stick_Left_X, Stick_Left_Y, Stick_Right_X, Stick_Right_Y); type Gamepad_Trigger is (Trigger_Left, Trigger_Right); type Gamepad_Buttons is array (Gamepad_Button) of Button_State with Component_Size => 1; type Changed_Gamepad_Buttons is array (Gamepad_Button) of Boolean with Component_Size => 1; type Axis_Position is delta 2.0 ** (-15) range -1.0 .. 1.0 - 2.0 ** (-15) with Small => 2.0 ** (-15), Size => 16; type Trigger_Position is delta 2.0 ** (-8) range 0.0 .. 1.0 - 2.0 ** (-8) with Small => 2.0 ** (-8), Size => 8; type Gamepad_Axes is array (Gamepad_Axis) of Axis_Position; type Gamepad_Triggers is array (Gamepad_Trigger) of Trigger_Position; type Gamepad_State is record Buttons : Gamepad_Buttons := (others => Released); Pressed : Changed_Gamepad_Buttons := (others => False); Released : Changed_Gamepad_Buttons := (others => False); Axes : Gamepad_Axes := (others => 0.0); Triggers : Gamepad_Triggers := (others => 0.0); end record; ---------------------------------------------------------------------------- type Battery_Capacity is range 0 .. 100; type Battery_Status is (Discharging, Charging, Not_Charging); type Battery_State (Is_Present : Boolean := False) is record case Is_Present is when True => Capacity : Battery_Capacity; Status : Battery_Status; when False => null; end case; end record; ---------------------------------------------------------------------------- type Color_Kind is (Red, Green, Blue); type RGB_Color is array (Color_Kind) of Normalized; type LED_State (Is_Present : Boolean := False) is record case Is_Present is when True => Brightness : Normalized; Color : RGB_Color; when False => null; end case; end record; ---------------------------------------------------------------------------- type Gamepad is tagged limited private; function Name (Object : Gamepad) return String; function Serial_Number (Object : Gamepad) return String; function GUID (Object : Gamepad) return GUID_String; function Connection (Object : Gamepad) return Connection_Kind; function State (Object : in out Gamepad) return Gamepad_State; function State (Object : Gamepad) return Battery_State; function State (Object : Gamepad) return LED_State; procedure Set_LED (Object : in out Gamepad; Brightness : Normalized; Color : RGB_Color); type Effect is private; function Rumble_Effect (Length, Offset : Duration; Strong, Weak : Normalized) return Effect; function Periodic_Effect (Length, Offset : Duration; Magnitude : Normalized; Attack, Fade : Duration) return Effect; procedure Play_Effect (Object : in out Gamepad; Subject : Effect); procedure Cancel_Effect (Object : in out Gamepad; Subject : Effect); function Effects (Object : Gamepad) return Natural; procedure Log_Information (Object : Gamepad); ---------------------------------------------------------------------------- procedure Set_Mappings (Text : String); procedure Initialize; procedure Poll; type Gamepad_Ptr is not null access all Gamepad; type Gamepad_Array is array (Positive range <>) of Gamepad_Ptr; function Gamepads return Gamepad_Array; ---------------------------------------------------------------------------- type Gamepad_Event_Listener is abstract tagged limited private; procedure On_Connect (Object : Gamepad_Event_Listener; Gamepad : Gamepad_Ptr) is abstract; procedure On_Disconnect (Object : Gamepad_Event_Listener; Gamepad : Gamepad_Ptr) is abstract; private type Axis_Value is delta 2.0 ** (-16) range -(2.0 ** 47) .. +(2.0 ** 47 - 2.0 ** (-16)); type Output_Kind is (Button, Axis, Trigger, None); type Output_Mapping (Kind : Output_Kind := None) is record case Kind is when Axis => Axis : AWT.Inputs.Gamepads.Gamepad_Axis; Scale : Axis_Value := 2.0; Offset : Axis_Value := 1.0; when Trigger => Trigger : AWT.Inputs.Gamepads.Gamepad_Trigger; when Button => Button : AWT.Inputs.Gamepads.Gamepad_Button; when None => null; end case; end record; type Side_Type is (Negative_Half, Positive_Half, Full_Range); subtype Hat_Side is Side_Type range Negative_Half .. Positive_Half; type Axis_Modifier is record Offset, Scale, Resolution : Axis_Value; end record; type Input_Mapping is record Modifier : Axis_Modifier; Side : Side_Type := Full_Range; Invert : Boolean := False; end record; type Mapping (Kind : Output_Kind := None) is record Input : Input_Mapping; Output : Output_Mapping (Kind); end record; type Axis_Mappings is array (AWT.Gamepads.Input_Axis) of Mapping; type Key_Mappings is array (AWT.Gamepads.Input_Button) of Mapping; type Hat_Mappings is array (AWT.Gamepads.Input_Hat, Hat_Side) of Mapping; type Gamepad is limited new AWT.Gamepads.Abstract_Gamepad with record Name, ID : SU.Unbounded_String; GUID : GUID_String; Gamepad : Gamepad_State; Axes : Axis_Mappings; Keys : Key_Mappings; Hats : Hat_Mappings; Has_Rumble : Boolean := False; Initialized : Boolean := False; Max_Effects : Natural := 0; end record; ---------------------------------------------------------------------------- type Effect is new AWT.Gamepads.Abstract_Effect; ---------------------------------------------------------------------------- type Gamepad_Event_Listener is abstract limited new Ada.Finalization.Limited_Controlled with null record; overriding procedure Initialize (Object : in out Gamepad_Event_Listener); overriding procedure Finalize (Object : in out Gamepad_Event_Listener); end AWT.Inputs.Gamepads;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 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. private with Ada.Finalization; private with Ada.Strings.Unbounded; private with AWT.Gamepads; package AWT.Inputs.Gamepads with SPARK_Mode => On is pragma Preelaborate; type Connection_Kind is (Disconnected, Wired, Wireless); type GUID_String is new String (1 .. 32) with Dynamic_Predicate => (for all C of GUID_String => C in '0' .. '9' | 'a' .. 'f'); type Normalized is new Float range 0.0 .. 1.0; ---------------------------------------------------------------------------- type Gamepad_Button is (Direction_Up, Direction_Right, Direction_Down, Direction_Left, Action_Down, Action_Right, Action_Left, Action_Up, Shoulder_Left, Shoulder_Right, Thumb_Left, Thumb_Right, Center_Left, Center_Right, Center_Logo); type Gamepad_Axis is (Stick_Left_X, Stick_Left_Y, Stick_Right_X, Stick_Right_Y); type Gamepad_Trigger is (Trigger_Left, Trigger_Right); type Gamepad_Buttons is array (Gamepad_Button) of Button_State with Component_Size => 1; type Changed_Gamepad_Buttons is array (Gamepad_Button) of Boolean with Component_Size => 1; type Axis_Position is delta 2.0 ** (-15) range -1.0 .. 1.0 - 2.0 ** (-15) with Small => 2.0 ** (-15), Size => 16; type Trigger_Position is delta 2.0 ** (-8) range 0.0 .. 1.0 - 2.0 ** (-8) with Small => 2.0 ** (-8), Size => 8; type Gamepad_Axes is array (Gamepad_Axis) of Axis_Position; type Gamepad_Triggers is array (Gamepad_Trigger) of Trigger_Position; type Gamepad_State is record Buttons : Gamepad_Buttons := (others => Released); Pressed : Changed_Gamepad_Buttons := (others => False); Released : Changed_Gamepad_Buttons := (others => False); Axes : Gamepad_Axes := (others => 0.0); Triggers : Gamepad_Triggers := (others => 0.0); end record; ---------------------------------------------------------------------------- type Battery_Capacity is range 0 .. 100; type Battery_Status is (Discharging, Charging, Not_Charging); type Battery_State (Is_Present : Boolean := False) is record case Is_Present is when True => Capacity : Battery_Capacity; Status : Battery_Status; when False => null; end case; end record; ---------------------------------------------------------------------------- type Color_Kind is (Red, Green, Blue); type RGB_Color is array (Color_Kind) of Normalized; type LED_State (Is_Present : Boolean := False) is record case Is_Present is when True => Brightness : Normalized; Color : RGB_Color; when False => null; end case; end record; ---------------------------------------------------------------------------- type Sensor_Axis_Value is delta 2.0 ** (-16) range -(2.0 ** 15) .. +(2.0 ** 15 - 2.0 ** (-16)) with Small => 2.0 ** (-16), Size => 32; type Sensor_Axis is (X, Y, Z, Rx, Ry, Rz); type Sensor_Axes is array (Sensor_Axis) of Sensor_Axis_Value; type Motion_State (Is_Present : Boolean := False) is record case Is_Present is when True => Axes : Sensor_Axes := (others => 0.0); when False => null; end case; end record; ---------------------------------------------------------------------------- type Gamepad is tagged limited private; function Name (Object : Gamepad) return String; function Serial_Number (Object : Gamepad) return String; function GUID (Object : Gamepad) return GUID_String; function Connection (Object : Gamepad) return Connection_Kind; function State (Object : in out Gamepad) return Gamepad_State; function State (Object : Gamepad) return Motion_State; function State (Object : Gamepad) return Battery_State; function State (Object : Gamepad) return LED_State; procedure Set_LED (Object : in out Gamepad; Brightness : Normalized; Color : RGB_Color); type Effect is private; function Rumble_Effect (Length, Offset : Duration; Strong, Weak : Normalized) return Effect; function Periodic_Effect (Length, Offset : Duration; Magnitude : Normalized; Attack, Fade : Duration) return Effect; procedure Play_Effect (Object : in out Gamepad; Subject : Effect); procedure Cancel_Effect (Object : in out Gamepad; Subject : Effect); function Effects (Object : Gamepad) return Natural; procedure Log_Information (Object : Gamepad); ---------------------------------------------------------------------------- procedure Set_Mappings (Text : String); procedure Initialize; procedure Poll; type Gamepad_Ptr is not null access all Gamepad; type Gamepad_Array is array (Positive range <>) of Gamepad_Ptr; function Gamepads return Gamepad_Array; ---------------------------------------------------------------------------- type Gamepad_Event_Listener is abstract tagged limited private; procedure On_Connect (Object : Gamepad_Event_Listener; Gamepad : Gamepad_Ptr) is abstract; procedure On_Disconnect (Object : Gamepad_Event_Listener; Gamepad : Gamepad_Ptr) is abstract; private type Axis_Value is delta 2.0 ** (-16) range -(2.0 ** 47) .. +(2.0 ** 47 - 2.0 ** (-16)); type Output_Kind is (Button, Axis, Trigger, None); type Output_Mapping (Kind : Output_Kind := None) is record case Kind is when Axis => Axis : AWT.Inputs.Gamepads.Gamepad_Axis; Scale : Axis_Value := 2.0; Offset : Axis_Value := 1.0; when Trigger => Trigger : AWT.Inputs.Gamepads.Gamepad_Trigger; when Button => Button : AWT.Inputs.Gamepads.Gamepad_Button; when None => null; end case; end record; type Side_Type is (Negative_Half, Positive_Half, Full_Range); subtype Hat_Side is Side_Type range Negative_Half .. Positive_Half; type Axis_Modifier is record Offset, Scale, Resolution : Axis_Value; end record; type Input_Mapping is record Modifier : Axis_Modifier; Side : Side_Type := Full_Range; Invert : Boolean := False; end record; type Mapping (Kind : Output_Kind := None) is record Input : Input_Mapping; Output : Output_Mapping (Kind); end record; type Axis_Mappings is array (AWT.Gamepads.Input_Axis) of Mapping; type Key_Mappings is array (AWT.Gamepads.Input_Button) of Mapping; type Hat_Mappings is array (AWT.Gamepads.Input_Hat, Hat_Side) of Mapping; type Sensor_Modifiers is array (AWT.Gamepads.Sensor_Axis) of Axis_Modifier; type Gamepad is limited new AWT.Gamepads.Abstract_Gamepad with record Name, ID : SU.Unbounded_String; GUID : GUID_String; Gamepad : Gamepad_State; Sensor : Motion_State; Axes : Axis_Mappings; Keys : Key_Mappings; Hats : Hat_Mappings; Sensors : Sensor_Modifiers; Has_Rumble : Boolean := False; Initialized : Boolean := False; Max_Effects : Natural := 0; end record; ---------------------------------------------------------------------------- type Effect is new AWT.Gamepads.Abstract_Effect; ---------------------------------------------------------------------------- type Gamepad_Event_Listener is abstract limited new Ada.Finalization.Limited_Controlled with null record; overriding procedure Initialize (Object : in out Gamepad_Event_Listener); overriding procedure Finalize (Object : in out Gamepad_Event_Listener); end AWT.Inputs.Gamepads;
Add support for motion sensor of gamepads
awt: Add support for motion sensor of gamepads Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
f0ea72fdcf2f283ed0fe03909decbdba815f4f94
src/ado-statements-create.adb
src/ado-statements-create.adb
----------------------------------------------------------------------- -- ADO Statements -- Database statements -- 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 body ADO.Statements.Create is -- ------------------------------ -- Create the query statement -- ------------------------------ function Create_Statement (Proxy : Query_Statement_Access) return Query_Statement is begin return Result : Query_Statement do Result.Query := Proxy.Get_Query; Result.Proxy := Proxy; Result.Proxy.Ref_Counter := 1; end return; end Create_Statement; -- ------------------------------ -- Create the delete statement -- ------------------------------ function Create_Statement (Proxy : Delete_Statement_Access) return Delete_Statement is begin return Result : Delete_Statement do Result.Query := Proxy.Get_Query; Result.Proxy := Proxy; Result.Proxy.Ref_Counter := 1; end return; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Proxy : Update_Statement_Access) return Update_Statement is begin return Result : Update_Statement do Result.Update := Proxy.Get_Update_Query; Result.Query := Result.Update.all'Access; Result.Proxy := Proxy; Result.Proxy.Ref_Counter := 1; end return; end Create_Statement; -- ------------------------------ -- Create the insert statement. -- ------------------------------ function Create_Statement (Proxy : Update_Statement_Access) return Insert_Statement is begin return Result : Insert_Statement do Result.Update := Proxy.Get_Update_Query; Result.Query := Result.Update.all'Access; Result.Proxy := Proxy; Result.Proxy.Ref_Counter := 1; end return; end Create_Statement; end ADO.Statements.Create;
----------------------------------------------------------------------- -- ADO Statements -- Database statements -- Copyright (C) 2009, 2010, 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Statements.Create is -- ------------------------------ -- Create the query statement -- ------------------------------ function Create_Statement (Proxy : in Query_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Query_Statement is begin Proxy.Set_Expander (Expander); Proxy.Query.Set_Expander (Expander); return Result : Query_Statement do Result.Query := Proxy.Get_Query; Result.Proxy := Proxy; Result.Proxy.Ref_Counter := 1; end return; end Create_Statement; -- ------------------------------ -- Create the delete statement -- ------------------------------ function Create_Statement (Proxy : in Delete_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Delete_Statement is begin Proxy.Set_Expander (Expander); Proxy.Query.Set_Expander (Expander); return Result : Delete_Statement do Result.Query := Proxy.Get_Query; Result.Proxy := Proxy; Result.Proxy.Ref_Counter := 1; end return; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Proxy : in Update_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Update_Statement is begin Proxy.Set_Expander (Expander); Proxy.Update.Set_Expander (Expander); return Result : Update_Statement do Result.Update := Proxy.Get_Update_Query; Result.Query := Result.Update.all'Access; Result.Proxy := Proxy; Result.Proxy.Ref_Counter := 1; end return; end Create_Statement; -- ------------------------------ -- Create the insert statement. -- ------------------------------ function Create_Statement (Proxy : in Update_Statement_Access; Expander : in ADO.Parameters.Expander_Access := null) return Insert_Statement is begin Proxy.Set_Expander (Expander); Proxy.Update.Set_Expander (Expander); return Result : Insert_Statement do Result.Update := Proxy.Get_Update_Query; Result.Query := Result.Update.all'Access; Result.Proxy := Proxy; Result.Proxy.Ref_Counter := 1; end return; end Create_Statement; end ADO.Statements.Create;
Configure the query/proxy expander with the new parameter added to the Create_Statement operations
Configure the query/proxy expander with the new parameter added to the Create_Statement operations
Ada
apache-2.0
stcarrez/ada-ado
aff1ce1215e30d0a7fd119a14f259dd1a8f8f215
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Test_Caller; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use ADO.Objects; use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use ADO.Objects; use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : constant ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; end Test_Blob; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Test_Caller; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use ADO.Objects; use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Unbounded_String; begin for I in 1 .. 127 loop Append (Name, Character'Val (I)); end loop; Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); Append (Name, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use ADO.Objects; use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); end Test_Blob; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); end Add_Tests; end ADO.Tests;
Update unit tests to check the blob
Update unit tests to check the blob
Ada
apache-2.0
Letractively/ada-ado
2129b0bc146c6a78f19ac04cddd2d31e6a68cf97
src/natools-web-containers.ads
src/natools-web-containers.ads
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Containres provides common containers for all website-wide -- -- persistent data. -- ------------------------------------------------------------------------------ with Ada.Calendar.Time_Zones; with Ada.Containers.Doubly_Linked_Lists; with Ada.Containers.Indefinite_Doubly_Linked_Lists; with Ada.Streams; with Natools.Constant_Indefinite_Ordered_Maps; with Natools.References; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Lockable; with Natools.Storage_Pools; package Natools.Web.Containers is type Date is record Time : Ada.Calendar.Time; Offset : Ada.Calendar.Time_Zones.Time_Offset; end record; package Date_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Date, S_Expressions.Less_Than); procedure Set_Dates (Map : in out Date_Maps.Constant_Map; Date_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize date database with then given list package Expression_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, S_Expressions.Caches.Cursor, S_Expressions.Less_Than, S_Expressions.Caches."="); procedure Set_Expressions (Map : in out Expression_Maps.Constant_Map; Expression_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize expression database with the given list package Expression_Map_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Expression_Maps.Constant_Map, S_Expressions.Less_Than, Expression_Maps."="); procedure Set_Expression_Maps (Map : in out Expression_Map_Maps.Constant_Map; Expression_Map_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize expression map database with the given list package Unsafe_Atom_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists (S_Expressions.Atom, Ada.Streams."="); procedure Append_Atoms (Target : in out Unsafe_Atom_Lists.List; Expression : in out S_Expressions.Lockable.Descriptor'Class); type Atom_Array is array (S_Expressions.Count range <>) of S_Expressions.Atom_Refs.Immutable_Reference; package Atom_Array_Refs is new References (Atom_Array, Storage_Pools.Access_In_Default_Pool'Storage_Pool, Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Source : Unsafe_Atom_Lists.List) return Atom_Array_Refs.Immutable_Reference; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Array_Refs.Immutable_Reference; package Atom_Row_Lists is new Ada.Containers.Doubly_Linked_Lists (Atom_Array_Refs.Immutable_Reference, Atom_Array_Refs."="); type Atom_Table is array (S_Expressions.Offset range <>) of Atom_Array_Refs.Immutable_Reference; package Atom_Table_Refs is new References (Atom_Table, Natools.Storage_Pools.Access_In_Default_Pool'Storage_Pool, Natools.Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Table_Refs.Immutable_Reference; function Create (Row_List : in Atom_Row_Lists.List) return Atom_Table_Refs.Immutable_Reference; type Atom_Set is private; Null_Atom_Set : constant Atom_Set; function Create (Source : in Atom_Array) return Atom_Set; function Create (Source : in Unsafe_Atom_Lists.List) return Atom_Set; function Contains (Set : in Atom_Set; Value : in S_Expressions.Atom) return Boolean; function Contains (Set : in Atom_Set; Value : in String) return Boolean; function Elements (Set : in Atom_Set) return Atom_Array_Refs.Immutable_Reference; type Identity is record User : S_Expressions.Atom_Refs.Immutable_Reference; Groups : Atom_Set; end record; Null_Identity : constant Identity; private type Atom_Set is record Elements : Atom_Array_Refs.Immutable_Reference; end record; function Elements (Set : in Atom_Set) return Atom_Array_Refs.Immutable_Reference is (Set.Elements); Null_Atom_Set : constant Atom_Set := (Elements => Atom_Array_Refs.Null_Immutable_Reference); Null_Identity : constant Identity := (User => S_Expressions.Atom_Refs.Null_Immutable_Reference, Groups => Null_Atom_Set); end Natools.Web.Containers;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Containres provides common containers for all website-wide -- -- persistent data. -- ------------------------------------------------------------------------------ with Ada.Calendar.Time_Zones; with Ada.Containers.Doubly_Linked_Lists; with Ada.Containers.Indefinite_Doubly_Linked_Lists; with Ada.Streams; with Natools.Constant_Indefinite_Ordered_Maps; with Natools.References; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Lockable; with Natools.Storage_Pools; package Natools.Web.Containers is type Date is record Time : Ada.Calendar.Time; Offset : Ada.Calendar.Time_Zones.Time_Offset; end record; package Date_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Date, S_Expressions.Less_Than); procedure Set_Dates (Map : in out Date_Maps.Constant_Map; Date_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize date database with then given list package Expression_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, S_Expressions.Caches.Cursor, S_Expressions.Less_Than, S_Expressions.Caches."="); procedure Set_Expressions (Map : in out Expression_Maps.Constant_Map; Expression_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize expression database with the given list package Expression_Map_Maps is new Constant_Indefinite_Ordered_Maps (S_Expressions.Atom, Expression_Maps.Constant_Map, S_Expressions.Less_Than, Expression_Maps."="); procedure Set_Expression_Maps (Map : in out Expression_Map_Maps.Constant_Map; Expression_Map_List : in out S_Expressions.Lockable.Descriptor'Class); -- (Re)initialize expression map database with the given list type Optional_Expression (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Value : S_Expressions.Caches.Cursor; end case; end record; package Unsafe_Atom_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists (S_Expressions.Atom, Ada.Streams."="); procedure Append_Atoms (Target : in out Unsafe_Atom_Lists.List; Expression : in out S_Expressions.Lockable.Descriptor'Class); type Atom_Array is array (S_Expressions.Count range <>) of S_Expressions.Atom_Refs.Immutable_Reference; package Atom_Array_Refs is new References (Atom_Array, Storage_Pools.Access_In_Default_Pool'Storage_Pool, Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Source : Unsafe_Atom_Lists.List) return Atom_Array_Refs.Immutable_Reference; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Array_Refs.Immutable_Reference; package Atom_Row_Lists is new Ada.Containers.Doubly_Linked_Lists (Atom_Array_Refs.Immutable_Reference, Atom_Array_Refs."="); type Atom_Table is array (S_Expressions.Offset range <>) of Atom_Array_Refs.Immutable_Reference; package Atom_Table_Refs is new References (Atom_Table, Natools.Storage_Pools.Access_In_Default_Pool'Storage_Pool, Natools.Storage_Pools.Access_In_Default_Pool'Storage_Pool); function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Atom_Table_Refs.Immutable_Reference; function Create (Row_List : in Atom_Row_Lists.List) return Atom_Table_Refs.Immutable_Reference; type Atom_Set is private; Null_Atom_Set : constant Atom_Set; function Create (Source : in Atom_Array) return Atom_Set; function Create (Source : in Unsafe_Atom_Lists.List) return Atom_Set; function Contains (Set : in Atom_Set; Value : in S_Expressions.Atom) return Boolean; function Contains (Set : in Atom_Set; Value : in String) return Boolean; function Elements (Set : in Atom_Set) return Atom_Array_Refs.Immutable_Reference; type Identity is record User : S_Expressions.Atom_Refs.Immutable_Reference; Groups : Atom_Set; end record; Null_Identity : constant Identity; private type Atom_Set is record Elements : Atom_Array_Refs.Immutable_Reference; end record; function Elements (Set : in Atom_Set) return Atom_Array_Refs.Immutable_Reference is (Set.Elements); Null_Atom_Set : constant Atom_Set := (Elements => Atom_Array_Refs.Null_Immutable_Reference); Null_Identity : constant Identity := (User => S_Expressions.Atom_Refs.Null_Immutable_Reference, Groups => Null_Atom_Set); end Natools.Web.Containers;
add a type for optional expressions
containers: add a type for optional expressions
Ada
isc
faelys/natools-web,faelys/natools-web
a68d49b425b5a86076bc7a93c07beda64e3bfdc3
src/util-streams-buffered.adb
src/util-streams-buffered.adb
----------------------------------------------------------------------- -- Util.Streams.Buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 2011, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Output := null; Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; Stream.No_Flush := False; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Input => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Buffered_Stream) is begin if Stream.Output /= null then Buffered_Stream'Class (Stream).Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Buffered_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Char : in Character) is begin if Stream.Write_Pos > Stream.Last then Stream.Flush; if Stream.Write_Pos > Stream.Last then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; Stream.Buffer (Stream.Write_Pos) := Stream_Element (Character'Pos (Char)); Stream.Write_Pos := Stream.Write_Pos + 1; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in String) is Start : Positive := Item'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Natural; Size : Natural; Char : Character; begin while Start <= Item'Last loop Size := Item'Last - Start + 1; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; while Size > 0 loop Char := Item (Start); Stream.Buffer (Pos) := Stream_Element (Character'Pos (Char)); Pos := Pos + 1; Start := Start + 1; Size := Size - 1; end loop; Stream.Write_Pos := Pos; end loop; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C))); end loop; end if; end Write; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Stream.Last - Pos + 1; if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data that the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then Stream.Flush; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Buffered_Stream) is begin if Stream.Write_Pos > 1 and not Stream.No_Flush then if Stream.Output = null then raise Ada.IO_Exceptions.Data_Error with "Output buffer is full"; else Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); Stream.Output.Flush; end if; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Buffered_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Buffered_Stream) is begin if Object.Buffer /= null then if Object.Output /= null then Object.Flush; end if; Free_Buffer (Object.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Buffered_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; end Util.Streams.Buffered;
----------------------------------------------------------------------- -- Util.Streams.Buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 2011, 2013, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Output := null; Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; Stream.No_Flush := False; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Input => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Buffered_Stream) is begin if Stream.Output /= null then Buffered_Stream'Class (Stream).Flush; Stream.Output.Close; end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Buffered_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Char : in Character) is begin if Stream.Write_Pos > Stream.Last then Stream.Flush; if Stream.Write_Pos > Stream.Last then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; Stream.Buffer (Stream.Write_Pos) := Stream_Element (Character'Pos (Char)); Stream.Write_Pos := Stream.Write_Pos + 1; end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Buffered_Stream; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Stream.Write (Character'Val (Val)); elsif Val <= 16#07FF# then Stream.Write (Character'Val (16#C0# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); elsif Val <= 16#0FFFF# then Stream.Write (Character'Val (16#E0# or Shift_Right (Val, 12))); Val := Val and 16#0FFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); else Val := Val and 16#1FFFFF#; Stream.Write (Character'Val (16#F0# or Shift_Right (Val, 18))); Val := Val and 16#3FFFF#; Stream.Write (Character'Val (16#E0# or Shift_Right (Val, 12))); Val := Val and 16#0FFF#; Stream.Write (Character'Val (16#80# or Shift_Right (Val, 6))); Stream.Write (Character'Val (16#80# or (Val and 16#03F#))); end if; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in String) is Start : Positive := Item'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Natural; Size : Natural; Char : Character; begin while Start <= Item'Last loop Size := Item'Last - Start + 1; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Natural (Stream.Last - Pos + 1); if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; while Size > 0 loop Char := Item (Start); Stream.Buffer (Pos) := Stream_Element (Character'Pos (Char)); Pos := Pos + 1; Start := Start + 1; Size := Size - 1; end loop; Stream.Write_Pos := Pos; end loop; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C))); end loop; end if; end Write; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then Stream.Flush; Pos := Stream.Write_Pos; Avail := Stream.Last - Pos + 1; if Avail = 0 then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data that the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then Stream.Flush; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Buffered_Stream) is begin if Stream.Write_Pos > 1 and not Stream.No_Flush then if Stream.Output = null then raise Ada.IO_Exceptions.Data_Error with "Output buffer is full"; else Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); Stream.Output.Flush; end if; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Buffered_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Buffered_Stream) is begin if Object.Buffer /= null then if Object.Output /= null then Object.Flush; end if; Free_Buffer (Object.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Buffered_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; end Util.Streams.Buffered;
Implement the Write_Wide procedure with UTF-8 conversion
Implement the Write_Wide procedure with UTF-8 conversion
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ef5b9c7a751f0bdbf48c52f0c3348eefae9debaa
src/sys/streams/util-streams-texts.adb
src/sys/streams/util-streams-texts.adb
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2019, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; procedure Initialize (Stream : in out Print_Stream; To : access Output_Stream'Class) is begin Stream.Initialize (Output => To, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Item => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write_Wide (C); end loop; end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item >= 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item >= 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : access Input_Stream'Class) is begin Stream.Initialize (Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error | Ada.IO_Exceptions.Device_Error | Ada.Io_Exceptions.End_Error => return; end Read_Line; end Util.Streams.Texts;
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2019, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; procedure Initialize (Stream : in out Print_Stream; To : access Output_Stream'Class) is begin Stream.Initialize (Output => To, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Item => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write_Wide (C); end loop; end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item >= 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item >= 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : access Input_Stream'Class) is begin Stream.Initialize (Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error | Ada.IO_Exceptions.Device_Error | Ada.IO_Exceptions.End_Error => return; end Read_Line; end Util.Streams.Texts;
Fix style name in exception
Fix style name in exception
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
62d764c8e27c054026ccc97303809d5c6aedfd0c
src/ado-parameters.ads
src/ado-parameters.ads
----------------------------------------------------------------------- -- ADO Parameters -- Parameters for queries -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Calendar; with Ada.Containers.Indefinite_Vectors; with ADO.Utils; with ADO.Drivers.Dialects; -- == Query Parameters == -- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost -- all database types including boolean, numbers, strings, dates and blob. Parameters are -- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types. -- -- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt> -- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name -- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list -- and uses the last position. In most cases, it is easier to bind a parameter with a name -- as follows: -- -- Query.Bind_Param ("name", "Joe"); -- -- and the SQL can use the following construct: -- -- SELECT * FROM user WHERE name = :name -- -- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it -- as a position index. Setting a parameter is easier: -- -- Query.Add_Param ("Joe"); -- -- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct: -- -- SELECT * FROM user WHERE name = ? -- -- === Parameter Expander === -- The parameter expander is a mechanism that allows to replace or inject values in the SQL -- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander -- is useful to replace parameters that are global to a session or to an application. -- package ADO.Parameters is use Ada.Strings.Unbounded; type Token is new String; type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER, T_INTEGER, T_BOOLEAN, T_BLOB); type Parameter (T : Parameter_Type; Len : Natural; Value_Len : Natural) is record Position : Natural := 0; Name : String (1 .. Len); case T is when T_NULL => null; when T_LONG_INTEGER => Long_Num : Long_Long_Integer := 0; when T_INTEGER => Num : Integer; when T_BOOLEAN => Bool : Boolean; when T_DATE => Time : Ada.Calendar.Time; when T_BLOB => Data : ADO.Blob_Ref; when others => Str : String (1 .. Value_Len); end case; end record; type Expander is limited interface; type Expander_Access is access all Expander'Class; -- Expand the name from the given group into a target parameter value to be used in -- the SQL query. The expander can look in a cache or in some configuration to find -- the value associated with the name and return it. The Expander can return a -- T_NULL when a value is not found or it may also raise some exception. function Expand (Instance : in Expander; Group : in String; Name : in String) return Parameter is abstract; type Abstract_List is abstract new Ada.Finalization.Controlled with private; type Abstract_List_Access is access all Abstract_List'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Params : in out Abstract_List; D : in ADO.Drivers.Dialects.Dialect_Access); -- Set the cache expander to be used when expanding the SQL. procedure Set_Expander (Params : in out Abstract_List; Expander : in ADO.Parameters.Expander_Access); -- Get the SQL dialect description object. function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access; -- Add the parameter in the list. procedure Add_Parameter (Params : in out Abstract_List; Param : in Parameter) is abstract; -- Set the parameters from another parameter list. procedure Set_Parameters (Parameters : in out Abstract_List; From : in Abstract_List'Class) is abstract; -- Return the number of parameters in the list. function Length (Params : in Abstract_List) return Natural is abstract; -- Return the parameter at the given position function Element (Params : in Abstract_List; Position : in Natural) return Parameter is abstract; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in Abstract_List; Position : in Natural; Process : not null access procedure (Element : in Parameter)) is abstract; -- Clear the list of parameters. procedure Clear (Parameters : in out Abstract_List) is abstract; -- Operations to bind a parameter procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Token); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Blob_Ref); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Utils.Identifier_Vector); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in ADO.Blob_Ref); procedure Bind_Null_Param (Params : in out Abstract_List; Position : in Natural); procedure Bind_Null_Param (Params : in out Abstract_List; Name : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Boolean); procedure Add_Param (Params : in out Abstract_List; Value : in Long_Long_Integer); procedure Add_Param (Params : in out Abstract_List; Value : in Identifier); procedure Add_Param (Params : in out Abstract_List; Value : in Integer); procedure Add_Param (Params : in out Abstract_List; Value : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Unbounded_String); procedure Add_Param (Params : in out Abstract_List; Value : in Ada.Calendar.Time); -- Add a null parameter. procedure Add_Null_Param (Params : in out Abstract_List); -- Expand the SQL string with the query parameters. The following parameters syntax -- are recognized and replaced: -- <ul> -- <li>? is replaced according to the current parameter index. The index is incremented -- after each occurrence of ? character. -- <li>:nnn is replaced by the parameter at index <b>nnn</b>. -- <li>:name is replaced by the parameter with the name <b>name</b> -- <li>$group[var-name] is replaced by using the expander interface. -- </ul> -- Parameter strings are escaped. When a parameter is not found, an empty string is used. -- Returns the expanded SQL string. function Expand (Params : in Abstract_List'Class; SQL : in String) return String; -- ------------------------------ -- List of parameters -- ------------------------------ -- The <b>List</b> is an implementation of the parameter list. type List is new Abstract_List with private; procedure Add_Parameter (Params : in out List; Param : in Parameter); procedure Set_Parameters (Params : in out List; From : in Abstract_List'Class); -- Return the number of parameters in the list. function Length (Params : in List) return Natural; -- Return the parameter at the given position function Element (Params : in List; Position : in Natural) return Parameter; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in List; Position : in Natural; Process : not null access procedure (Element : in Parameter)); -- Clear the list of parameters. procedure Clear (Params : in out List); private function Compare_On_Name (Left, Right : in Parameter) return Boolean; package Parameter_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Parameter, "=" => Compare_On_Name); type Abstract_List is abstract new Ada.Finalization.Controlled with record Dialect : ADO.Drivers.Dialects.Dialect_Access := null; Expander : Expander_Access; end record; type List is new Abstract_List with record Params : Parameter_Vectors.Vector; end record; end ADO.Parameters;
----------------------------------------------------------------------- -- ADO Parameters -- Parameters for queries -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; with Ada.Calendar; with Ada.Containers.Indefinite_Vectors; with ADO.Utils; with ADO.Drivers.Dialects; -- == Query Parameters == -- Query parameters are represented by the <tt>Parameter</tt> type which can represent almost -- all database types including boolean, numbers, strings, dates and blob. Parameters are -- put in a list represented by the <tt>Abstract_List</tt> or <tt>List</tt> types. -- -- A parameter is added by using either the <tt>Bind_Param</tt> or the <tt>Add_Param</tt> -- operation. The <tt>Bind_Param</tt> operation allows to specify either the parameter name -- or its position. The <tt>Add_Param</tt> operation adds the parameter at end of the list -- and uses the last position. In most cases, it is easier to bind a parameter with a name -- as follows: -- -- Query.Bind_Param ("name", "Joe"); -- -- and the SQL can use the following construct: -- -- SELECT * FROM user WHERE name = :name -- -- When the <tt>Add_Param</tt> is used, the parameter is not associated with any name but it -- as a position index. Setting a parameter is easier: -- -- Query.Add_Param ("Joe"); -- -- but the SQL cannot make any reference to names and must use the <tt>?</tt> construct: -- -- SELECT * FROM user WHERE name = ? -- -- === Parameter Expander === -- The parameter expander is a mechanism that allows to replace or inject values in the SQL -- query by looking at an operation provided by the <tt>Expander</tt> interface. Such expander -- is useful to replace parameters that are global to a session or to an application. -- package ADO.Parameters is use Ada.Strings.Unbounded; type Token is new String; type Parameter_Type is (T_NULL, T_STRING, T_TOKEN, T_LIST, T_DATE, T_LONG_INTEGER, T_INTEGER, T_BOOLEAN, T_BLOB); type Parameter (T : Parameter_Type; Len : Natural; Value_Len : Natural) is record Position : Natural := 0; Name : String (1 .. Len); case T is when T_NULL => null; when T_LONG_INTEGER => Long_Num : Long_Long_Integer := 0; when T_INTEGER => Num : Integer; when T_BOOLEAN => Bool : Boolean; when T_DATE => Time : Ada.Calendar.Time; when T_BLOB => Data : ADO.Blob_Ref; when others => Str : String (1 .. Value_Len); end case; end record; type Expander is limited interface; type Expander_Access is access all Expander'Class; -- Expand the name from the given group into a target parameter value to be used in -- the SQL query. The expander can look in a cache or in some configuration to find -- the value associated with the name and return it. The Expander can return a -- T_NULL when a value is not found or it may also raise some exception. function Expand (Instance : in Expander; Group : in String; Name : in String) return Parameter is abstract; type Abstract_List is abstract new Ada.Finalization.Controlled with private; type Abstract_List_Access is access all Abstract_List'Class; -- Set the SQL dialect description object. procedure Set_Dialect (Params : in out Abstract_List; D : in ADO.Drivers.Dialects.Dialect_Access); -- Set the cache expander to be used when expanding the SQL. procedure Set_Expander (Params : in out Abstract_List; Expander : in ADO.Parameters.Expander_Access); -- Get the SQL dialect description object. function Get_Dialect (From : in Abstract_List) return ADO.Drivers.Dialects.Dialect_Access; -- Add the parameter in the list. procedure Add_Parameter (Params : in out Abstract_List; Param : in Parameter) is abstract; -- Set the parameters from another parameter list. procedure Set_Parameters (Parameters : in out Abstract_List; From : in Abstract_List'Class) is abstract; -- Return the number of parameters in the list. function Length (Params : in Abstract_List) return Natural is abstract; -- Return the parameter at the given position function Element (Params : in Abstract_List; Position : in Natural) return Parameter is abstract; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in Abstract_List; Position : in Natural; Process : not null access procedure (Element : in Parameter)) is abstract; -- Clear the list of parameters. procedure Clear (Parameters : in out Abstract_List) is abstract; -- Operations to bind a parameter procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in Token); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Blob_Ref); procedure Bind_Param (Params : in out Abstract_List; Name : in String; Value : in ADO.Utils.Identifier_Vector); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Boolean); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Long_Long_Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Identifier); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Integer); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Entity_Type); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Unbounded_String); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in Ada.Calendar.Time); procedure Bind_Param (Params : in out Abstract_List; Position : in Natural; Value : in ADO.Blob_Ref); procedure Bind_Null_Param (Params : in out Abstract_List; Position : in Natural); procedure Bind_Null_Param (Params : in out Abstract_List; Name : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Boolean); procedure Add_Param (Params : in out Abstract_List; Value : in Long_Long_Integer); procedure Add_Param (Params : in out Abstract_List; Value : in Identifier); procedure Add_Param (Params : in out Abstract_List; Value : in Integer); procedure Add_Param (Params : in out Abstract_List; Value : in String); procedure Add_Param (Params : in out Abstract_List; Value : in Unbounded_String); procedure Add_Param (Params : in out Abstract_List; Value : in Ada.Calendar.Time); -- Add a null parameter. procedure Add_Null_Param (Params : in out Abstract_List); -- Expand the SQL string with the query parameters. The following parameters syntax -- are recognized and replaced: -- <ul> -- <li>? is replaced according to the current parameter index. The index is incremented -- after each occurrence of ? character. -- <li>:nnn is replaced by the parameter at index <b>nnn</b>. -- <li>:name is replaced by the parameter with the name <b>name</b> -- <li>$group[var-name] is replaced by using the expander interface. -- </ul> -- Parameter strings are escaped. When a parameter is not found, an empty string is used. -- Returns the expanded SQL string. function Expand (Params : in Abstract_List'Class; SQL : in String) return String; -- ------------------------------ -- List of parameters -- ------------------------------ -- The <b>List</b> is an implementation of the parameter list. type List is new Abstract_List with private; procedure Add_Parameter (Params : in out List; Param : in Parameter); procedure Set_Parameters (Params : in out List; From : in Abstract_List'Class); -- Return the number of parameters in the list. function Length (Params : in List) return Natural; -- Return the parameter at the given position function Element (Params : in List; Position : in Natural) return Parameter; -- Execute the <b>Process</b> procedure with the given parameter as argument. procedure Query_Element (Params : in List; Position : in Natural; Process : not null access procedure (Element : in Parameter)); -- Clear the list of parameters. procedure Clear (Params : in out List); private function Compare_On_Name (Left, Right : in Parameter) return Boolean; package Parameter_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Parameter, "=" => Compare_On_Name); type Abstract_List is abstract new Ada.Finalization.Controlled with record Dialect : ADO.Drivers.Dialects.Dialect_Access := null; Expander : Expander_Access; end record; type List is new Abstract_List with record Params : Parameter_Vectors.Vector; end record; end ADO.Parameters;
Fix style warning reported by GNAT 2018
Fix style warning reported by GNAT 2018
Ada
apache-2.0
stcarrez/ada-ado
74cd56ddfc4d4031503a18226adee625c8b23598
src/util-concurrent-pools.adb
src/util-concurrent-pools.adb
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- Copyright (C) 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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) is begin From.List.Get_Instance (Item); 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; -- ------------------------------ -- 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;
Add the Wait parameter to Get_Instance and raise the Timeout exception if no object from the pool was available before the delay expired
Add the Wait parameter to Get_Instance and raise the Timeout exception if no object from the pool was available before the delay expired
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6dfb82314b21bddc045f1bd4d32c048cf94c049a
src/util-serialize-io-csv.ads
src/util-serialize-io-csv.ads
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with Util.Streams.Texts; -- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files. -- -- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files package Util.Serialize.IO.CSV is type Row_Type is new Natural; type Column_Type is new Positive; -- ------------------------------ -- CSV Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a CSV output stream. -- The stream object takes care of the CSV escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character); -- Enable or disable the double quotes by default for strings. procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean); -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. procedure Write_Cell (Stream : in out Output_Stream; Value : in String); procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer); procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean); procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new row. procedure New_Row (Stream : in out Output_Stream); -- 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); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- CSV Parser -- ------------------------------ -- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly -- in Ada records. type Parser is new Serialize.IO.Parser with private; -- Get the header name for the given column. -- If there was no header line, build a default header for the column. function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String; -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type); -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character); -- Get the field separator. function Get_Field_Separator (Handler : in Parser) return Character; -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character); -- Get the comment separator. Returns ASCII.NUL if comments are not supported. function Get_Comment_Separator (Handler : in Parser) return Character; -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True); -- Parse the stream using the CSV parser. overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class); -- Get the current location (file and line) to report an error message. overriding function Get_Location (Handler : in Parser) return String; private type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Max_Columns : Column_Type := 1; Column : Column_Type := 1; Row : Row_Type := 0; Separator : Character := ','; Quote : Boolean := True; end record; type Parser is new Util.Serialize.IO.Parser with record Has_Header : Boolean := True; Line_Number : Natural := 1; Row : Row_Type := 0; Headers : Util.Strings.Vectors.Vector; Separator : Character := ','; Comment : Character := ASCII.NUL; Use_Default_Headers : Boolean := False; end record; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with Util.Streams.Texts; -- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files. -- -- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files package Util.Serialize.IO.CSV is type Row_Type is new Natural; type Column_Type is new Positive; -- ------------------------------ -- CSV Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a CSV output stream. -- The stream object takes care of the CSV escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character); -- Enable or disable the double quotes by default for strings. procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean); -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. procedure Write_Cell (Stream : in out Output_Stream; Value : in String); procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer); procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean); procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new row. procedure New_Row (Stream : in out Output_Stream); -- 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); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- CSV Parser -- ------------------------------ -- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly -- in Ada records. type Parser is new Serialize.IO.Parser with private; -- Get the header name for the given column. -- If there was no header line, build a default header for the column. function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String; -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type); -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character); -- Get the field separator. function Get_Field_Separator (Handler : in Parser) return Character; -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character); -- Get the comment separator. Returns ASCII.NUL if comments are not supported. function Get_Comment_Separator (Handler : in Parser) return Character; -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True); -- Parse the stream using the CSV parser. overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class); -- Get the current location (file and line) to report an error message. overriding function Get_Location (Handler : in Parser) return String; private type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Max_Columns : Column_Type := 1; Column : Column_Type := 1; Row : Row_Type := 0; Separator : Character := ','; Quote : Boolean := True; end record; type Parser is new Util.Serialize.IO.Parser with record Has_Header : Boolean := True; Line_Number : Natural := 1; Row : Row_Type := 0; Headers : Util.Strings.Vectors.Vector; Separator : Character := ','; Comment : Character := ASCII.NUL; Use_Default_Headers : Boolean := False; Sink : access Reader'Class; end record; end Util.Serialize.IO.CSV;
Add a Sink parameter to the Parse procedure
Add a Sink parameter to the Parse procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fe52b399ce093702b8802b8e8cbe5ffc4cbfb5db
awa/src/awa-users-principals.adb
awa/src/awa-users-principals.adb
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- 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. ----------------------------------------------------------------------- package body AWA.Users.Principals is -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return From.User.Get_Name; end Get_Name; -- ------------------------------ -- Get the principal identifier (name) -- ------------------------------ function Get_Id (From : in Principal) return String is begin return From.User.Get_Name; end Get_Id; -- ------------------------------ -- Get the user associated with the principal. -- ------------------------------ function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is begin return From.User; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (From : in Principal) return ADO.Identifier is begin return From.User.Get_Id; end Get_User_Identifier; -- ------------------------------ -- Get the connection session used by the user. -- ------------------------------ function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is begin return From.Session; end Get_Session; -- ------------------------------ -- Get the connection session identifier used by the user. -- ------------------------------ function Get_Session_Identifier (From : in Principal) return ADO.Identifier is begin return From.Session.Get_Id; end Get_Session_Identifier; -- ------------------------------ -- Create a principal for the given user. -- ------------------------------ function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access is Result : constant Principal_Access := new Principal; begin Result.User := User; Result.Session := Session; return Result; end Create; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. -- ------------------------------ function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier is use type ASF.Principals.Principal_Access; begin if From = null then return ADO.NO_IDENTIFIER; elsif not (From.all in Principal'Class) then return ADO.NO_IDENTIFIER; else return Principal'Class (From.all).Get_User_Identifier; end if; end Get_User_Identifier; end AWA.Users.Principals;
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Users.Principals is -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return From.User.Get_Name; end Get_Name; -- ------------------------------ -- Get the principal identifier (name) -- ------------------------------ function Get_Id (From : in Principal) return String is begin return From.User.Get_Name; end Get_Id; -- ------------------------------ -- Get the user associated with the principal. -- ------------------------------ function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is begin return From.User; end Get_User; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. -- ------------------------------ function Get_User_Identifier (From : in Principal) return ADO.Identifier is begin return From.User.Get_Id; end Get_User_Identifier; -- ------------------------------ -- Get the connection session used by the user. -- ------------------------------ function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is begin return From.Session; end Get_Session; -- ------------------------------ -- Get the connection session identifier used by the user. -- ------------------------------ function Get_Session_Identifier (From : in Principal) return ADO.Identifier is begin return From.Session.Get_Id; end Get_Session_Identifier; -- ------------------------------ -- Create a principal for the given user. -- ------------------------------ function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access is Result : constant Principal_Access := new Principal; begin Result.User := User; Result.Session := Session; return Result; end Create; -- ------------------------------ -- Create a principal for the given user. -- ------------------------------ function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal is begin return Result : Principal do Result.User := User; Result.Session := Session; end return; end Create; -- ------------------------------ -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. -- ------------------------------ function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier is use type ASF.Principals.Principal_Access; begin if From = null then return ADO.NO_IDENTIFIER; elsif not (From.all in Principal'Class) then return ADO.NO_IDENTIFIER; else return Principal'Class (From.all).Get_User_Identifier; end if; end Get_User_Identifier; end AWA.Users.Principals;
Implement the new Create operation to build a principal from a user/session
Implement the new Create operation to build a principal from a user/session
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
31f10974b069933e9c0691f9e45d740bc6373484
tools/druss-commands-devices.ads
tools/druss-commands-devices.ads
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Druss.Commands.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; Context : in out Context_Type); -- Execute a status command to report information about the Bbox. overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type); end Druss.Commands.Devices;
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Druss.Commands.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 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;
Add a device selector to the Do_List procedure
Add a device selector to the Do_List procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
40c72b4fbdc7d7da01f695a01ca86431905227af
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
Declare the Invitation_Bean with the Load, Send and Accept_Invitation procedures
Declare the Invitation_Bean with the Load, Send and Accept_Invitation procedures
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e77f28704eaf661bb164b9e15afe8f36c1904ec6
src/util-serialize-mappers-vector_mapper.adb
src/util-serialize-mappers-vector_mapper.adb
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Vector_Mapper -- Mapper for vector types -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body Util.Serialize.Mappers.Vector_Mapper is use Vectors; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers.Vector_Mapper", Util.Log.WARN_LEVEL); Key : Util.Serialize.Contexts.Data_Key; -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. -- ----------------------- -- Get the vector object. -- ----------------------- function Get_Vector (Data : in Vector_Data) return Vector_Type_Access is begin return Data.Vector; end Get_Vector; -- ----------------------- -- Set the vector object. -- ----------------------- procedure Set_Vector (Data : in out Vector_Data; Vector : in Vector_Type_Access) is begin Data.Vector := Vector; end Set_Vector; -- ----------------------- -- Record mapper -- ----------------------- -- ----------------------- -- Set the <b>Data</b> vector in the context. -- ----------------------- procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Data : in Vector_Type_Access) is Data_Context : Vector_Data_Access := new Vector_Data; begin Data_Context.Vector := Data; Data_Context.Position := Index_Type'First; Ctx.Set_Data (Key => Key, Content => Data_Context.all'Unchecked_Access); end Set_Context; -- ----------------------- -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. -- ----------------------- procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Handler); procedure Process (Element : in out Element_Type); procedure Process (Element : in out Element_Type) is begin Element_Mapper.Set_Member (Map, Element, Value); end Process; D : constant Contexts.Data_Access := Ctx.Get_Data (Key); begin Log.Debug ("Updating vector element"); if not (D.all in Vector_Data'Class) then raise Util.Serialize.Contexts.No_Data; end if; declare DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access; begin if DE.Vector = null then raise Util.Serialize.Contexts.No_Data; end if; -- Update the element through the generic procedure Update_Element (DE.Vector.all, DE.Position - 1, Process'Access); end; end Execute; procedure Set_Mapping (Into : in out Mapper; Inner : in Element_Mapper.Mapper_Access) is begin Into.Mapper := Inner.all'Unchecked_Access; Into.Map.Bind (Inner); end Set_Mapping; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String) return Util.Serialize.Mappers.Mapper_Access is begin return Controller.Mapper.Find_Mapper (Name); end Find_Mapper; overriding procedure Initialize (Controller : in out Mapper) is begin Controller.Mapper := Controller.Map'Unchecked_Access; end Initialize; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is pragma Unreferenced (Handler); procedure Set_Context (Item : in out Element_Type); D : constant Contexts.Data_Access := Context.Get_Data (Key); procedure Set_Context (Item : in out Element_Type) is begin Element_Mapper.Set_Context (Ctx => Context, Element => Item'Unrestricted_Access); end Set_Context; begin Log.Debug ("Creating vector element {0}", Name); if not (D.all in Vector_Data'Class) then raise Util.Serialize.Contexts.No_Data; end if; declare DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access; begin if DE.Vector = null then raise Util.Serialize.Contexts.No_Data; end if; Insert_Space (DE.Vector.all, DE.Position); DE.Vector.Update_Element (Index => DE.Position, Process => Set_Context'Access); DE.Position := DE.Position + 1; end; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin null; end Finish_Object; -- ----------------------- -- Write the element on the stream using the mapper description. -- ----------------------- procedure Write (Handler : in Mapper; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Vectors.Vector) is Pos : Vectors.Cursor := Element.First; begin Stream.Start_Array (Element.Length); while Vectors.Has_Element (Pos) loop Element_Mapper.Write (Handler.Mapper.all, Handler.Map.Get_Getter, Stream, Vectors.Element (Pos)); Vectors.Next (Pos); end loop; Stream.End_Array; end Write; begin -- Allocate the unique data key. Util.Serialize.Contexts.Allocate (Key); end Util.Serialize.Mappers.Vector_Mapper;
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Vector_Mapper -- Mapper for vector types -- Copyright (C) 2010, 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body Util.Serialize.Mappers.Vector_Mapper is use Vectors; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers.Vector_Mapper", Util.Log.WARN_LEVEL); Key : Util.Serialize.Contexts.Data_Key; -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. -- ----------------------- -- Get the vector object. -- ----------------------- function Get_Vector (Data : in Vector_Data) return Vector_Type_Access is begin return Data.Vector; end Get_Vector; -- ----------------------- -- Set the vector object. -- ----------------------- procedure Set_Vector (Data : in out Vector_Data; Vector : in Vector_Type_Access) is begin Data.Vector := Vector; end Set_Vector; -- ----------------------- -- Record mapper -- ----------------------- -- ----------------------- -- Set the <b>Data</b> vector in the context. -- ----------------------- procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Data : in Vector_Type_Access) is Data_Context : constant Vector_Data_Access := new Vector_Data; begin Data_Context.Vector := Data; Data_Context.Position := Index_Type'First; Ctx.Set_Data (Key => Key, Content => Data_Context.all'Unchecked_Access); end Set_Context; -- ----------------------- -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. -- ----------------------- procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Handler); procedure Process (Element : in out Element_Type); procedure Process (Element : in out Element_Type) is begin Element_Mapper.Set_Member (Map, Element, Value); end Process; D : constant Contexts.Data_Access := Ctx.Get_Data (Key); begin Log.Debug ("Updating vector element"); if not (D.all in Vector_Data'Class) then raise Util.Serialize.Contexts.No_Data; end if; declare DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access; begin if DE.Vector = null then raise Util.Serialize.Contexts.No_Data; end if; -- Update the element through the generic procedure Update_Element (DE.Vector.all, DE.Position - 1, Process'Access); end; end Execute; procedure Set_Mapping (Into : in out Mapper; Inner : in Element_Mapper.Mapper_Access) is begin Into.Mapper := Inner.all'Unchecked_Access; Into.Map.Bind (Inner); end Set_Mapping; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String) return Util.Serialize.Mappers.Mapper_Access is begin return Controller.Mapper.Find_Mapper (Name); end Find_Mapper; overriding procedure Initialize (Controller : in out Mapper) is begin Controller.Mapper := Controller.Map'Unchecked_Access; end Initialize; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is pragma Unreferenced (Handler); procedure Set_Context (Item : in out Element_Type); D : constant Contexts.Data_Access := Context.Get_Data (Key); procedure Set_Context (Item : in out Element_Type) is begin Element_Mapper.Set_Context (Ctx => Context, Element => Item'Unrestricted_Access); end Set_Context; begin Log.Debug ("Creating vector element {0}", Name); if not (D.all in Vector_Data'Class) then raise Util.Serialize.Contexts.No_Data; end if; declare DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access; begin if DE.Vector = null then raise Util.Serialize.Contexts.No_Data; end if; Insert_Space (DE.Vector.all, DE.Position); DE.Vector.Update_Element (Index => DE.Position, Process => Set_Context'Access); DE.Position := DE.Position + 1; end; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin null; end Finish_Object; -- ----------------------- -- Write the element on the stream using the mapper description. -- ----------------------- procedure Write (Handler : in Mapper; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Vectors.Vector) is Pos : Vectors.Cursor := Element.First; begin Stream.Start_Array (Element.Length); while Vectors.Has_Element (Pos) loop Element_Mapper.Write (Handler.Mapper.all, Handler.Map.Get_Getter, Stream, Vectors.Element (Pos)); Vectors.Next (Pos); end loop; Stream.End_Array; end Write; begin -- Allocate the unique data key. Util.Serialize.Contexts.Allocate (Key); end Util.Serialize.Mappers.Vector_Mapper;
Fix compilation warning reported by gcc 4.7
Fix compilation warning reported by gcc 4.7
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7e5b5536ba4947f5be12c3d4c176294649983412
src/util-beans-objects-maps.ads
src/util-beans-objects-maps.ads
----------------------------------------------------------------------- -- Util.Beans.Objects.Maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Beans.Basic; package Util.Beans.Objects.Maps is package Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Object, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); subtype Cursor is Maps.Cursor; subtype Map is Maps.Map; -- Make all the Maps operations available (a kind of 'use Maps' for anybody). function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length; function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty; procedure Clear (Container : in out Map) renames Maps.Clear; function Key (Position : Cursor) return String renames Maps.Key; procedure Include (Container : in out Map; Key : in String; New_Item : in Object) renames Maps.Include; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : String; Element : Object)) renames Maps.Query_Element; function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element; function Element (Position : Cursor) return Object renames Maps.Element; procedure Next (Position : in out Cursor) renames Maps.Next; function Next (Position : Cursor) return Cursor renames Maps.Next; function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : Cursor; Right : String) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : String; Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map renames Maps.Copy; -- ------------------------------ -- 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 Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Map_Bean; Name : in String) return Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object); -- Create an object that contains a <tt>Map_Bean</tt> instance. function Create return Object; private type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record; end Util.Beans.Objects.Maps;
----------------------------------------------------------------------- -- Util.Beans.Objects.Maps -- Object maps -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Beans.Basic; package Util.Beans.Objects.Maps is package Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Object, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); subtype Cursor is Maps.Cursor; subtype Map is Maps.Map; -- Make all the Maps operations available (a kind of 'use Maps' for anybody). function Length (Container : in Map) return Ada.Containers.Count_Type renames Maps.Length; function Is_Empty (Container : in Map) return Boolean renames Maps.Is_Empty; procedure Clear (Container : in out Map) renames Maps.Clear; function Key (Position : Cursor) return String renames Maps.Key; procedure Include (Container : in out Map; Key : in String; New_Item : in Object) renames Maps.Include; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Key : String; Element : Object)) renames Maps.Query_Element; function Has_Element (Position : Cursor) return Boolean renames Maps.Has_Element; function Element (Position : Cursor) return Object renames Maps.Element; procedure Next (Position : in out Cursor) renames Maps.Next; function Next (Position : Cursor) return Cursor renames Maps.Next; function Equivalent_Keys (Left, Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : Cursor; Right : String) return Boolean renames Maps.Equivalent_Keys; function Equivalent_Keys (Left : String; Right : Cursor) return Boolean renames Maps.Equivalent_Keys; function Copy (Source : Maps.Map; Capacity : in Ada.Containers.Count_Type) return Maps.Map renames Maps.Copy; -- ------------------------------ -- 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 Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with private; type Map_Bean_Access is access all Map_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 : in Map_Bean; Name : in String) return Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. procedure Set_Value (From : in out Map_Bean; Name : in String; Value : in Object); -- Create an object that contains a <tt>Map_Bean</tt> instance. function Create return Object; private type Map_Bean is new Maps.Map and Util.Beans.Basic.Bean with null record; end Util.Beans.Objects.Maps;
Declare the Map_Bean_Access type
Declare the Map_Bean_Access type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
851e5d1f5658262e8076839351ebb512bba5ee7b
UNIT_TESTS/init_001.adb
UNIT_TESTS/init_001.adb
with Test; with OpenAL.Context; with OpenAL.Context.Error; procedure init_001 is package ALC renames OpenAL.Context; package ALC_Error renames OpenAL.Context.Error; Device : ALC.Device_t; Context : ALC.Context_t; Current_OK : Boolean; TC : Test.Context_t; use type ALC.Device_t; use type ALC.Context_t; use type ALC_Error.Error_t; begin Test.Initialize (Test_Context => TC, Program => "init_001", Test_DB => "TEST_DB", Test_Results => "TEST_RESULTS"); Device := ALC.Open_Default_Device; Test.Check (TC, 1, Device /= ALC.Invalid_Device, "Device /= ALC.Invalid_Device"); Test.Check (TC, 2, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); Context := ALC.Create_Context (Device); Test.Check (TC, 3, Context /= ALC.Invalid_Context, "Context /= ALC.Invalid_Context"); Test.Check (TC, 4, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); Current_OK := ALC.Make_Context_Current (Context); Test.Check (TC, 5, Current_OK, "Current_OK"); Test.Check (TC, 6, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); Current_OK := ALC.Make_Context_Current (ALC.Null_Context); Test.Check (TC, 7, Current_OK, "Current_OK"); Test.Check (TC, 8, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); ALC.Destroy_Context (Context); Test.Check (TC, 9, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); ALC.Close_Device (Device); Test.Check (TC, 10, Device = ALC.Invalid_Device, "Device = ALC.Invalid_Device"); end init_001;
with Test; with OpenAL.Context; with OpenAL.Context.Error; procedure init_001 is package ALC renames OpenAL.Context; package ALC_Error renames OpenAL.Context.Error; Device : ALC.Device_t; Context : ALC.Context_t; Current_OK : Boolean; TC : Test.Context_t; use type ALC.Device_t; use type ALC.Context_t; use type ALC_Error.Error_t; begin Test.Initialize (Test_Context => TC, Program => "init_001", Test_DB => "TEST_DB", Test_Results => "TEST_RESULTS"); Device := ALC.Open_Default_Device; Test.Check (TC, 1, Device /= ALC.Invalid_Device, "Device /= ALC.Invalid_Device"); Test.Check (TC, 2, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); pragma Assert (Device /= ALC.Invalid_Device); Context := ALC.Create_Context (Device); Test.Check (TC, 3, Context /= ALC.Invalid_Context, "Context /= ALC.Invalid_Context"); Test.Check (TC, 4, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); pragma Assert (Context /= ALC.Invalid_Context); Current_OK := ALC.Make_Context_Current (Context); Test.Check (TC, 5, Current_OK, "Current_OK"); Test.Check (TC, 6, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); Current_OK := ALC.Make_Context_Current (ALC.Null_Context); Test.Check (TC, 7, Current_OK, "Current_OK"); Test.Check (TC, 8, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); ALC.Destroy_Context (Context); Test.Check (TC, 9, ALC_Error.Get_Error (Device) = ALC_Error.No_Error, "ALC_Error.Get_Error (Device) = ALC_Error.No_Error"); ALC.Close_Device (Device); Test.Check (TC, 10, Device = ALC.Invalid_Device, "Device = ALC.Invalid_Device"); end init_001;
Add assertions before running tests that may give incorrect results dependent on previous tests
Add assertions before running tests that may give incorrect results dependent on previous tests
Ada
isc
io7m/coreland-openal-ada,io7m/coreland-openal-ada
94a86e9b6408bd783fb7159789f00458c6694e91
src/orka/interface/orka-rendering-programs-uniforms.ads
src/orka/interface/orka-rendering-programs-uniforms.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Containers.Indefinite_Holders; with GL.Low_Level.Enums; with GL.Objects.Programs.Uniforms; with GL.Objects.Textures; with GL.Types; with Orka.Transforms.Singles.Matrices; with Orka.Transforms.Doubles.Matrices; package Orka.Rendering.Programs.Uniforms is pragma Preelaborate; package LE renames GL.Low_Level.Enums; use type LE.Texture_Kind; use type LE.Resource_Type; package TS renames Transforms.Singles.Matrices; package TD renames Transforms.Doubles.Matrices; type Uniform (Kind : LE.Resource_Type) is tagged private; procedure Set_Matrix (Object : Uniform; Value : TS.Matrix4); procedure Set_Matrix (Object : Uniform; Value : TD.Matrix4); procedure Set_Vector (Object : Uniform; Value : TS.Vector4); procedure Set_Vector (Object : Uniform; Value : TD.Vector4); procedure Set_Single (Object : Uniform; Value : GL.Types.Single); procedure Set_Double (Object : Uniform; Value : GL.Types.Double); procedure Set_Int (Object : Uniform; Value : GL.Types.Int); procedure Set_UInt (Object : Uniform; Value : GL.Types.UInt); procedure Set_Boolean (Object : Uniform; Value : Boolean); function GL_Uniform (Object : Uniform) return GL.Objects.Programs.Uniforms.Uniform with Inline; ----------------------------------------------------------------------------- type Uniform_Sampler (Kind : LE.Texture_Kind) is tagged private; procedure Set_Texture (Object : Uniform_Sampler; Texture : GL.Objects.Textures.Texture_Base'Class; Binding : Natural) with Pre => Texture.Kind = Object.Kind; -- TODO Add pre condition to check Texture.Format matches Sampler_Kind -- (see https://www.khronos.org/opengl/wiki/Sampler_(GLSL)#Sampler_types) -- Set the binding point of the uniform sampler and bind the -- given texture to the corresponding texture unit ----------------------------------------------------------------------------- type Uniform_Image (Kind : LE.Texture_Kind) is tagged private; procedure Set_Image (Object : Uniform_Image; Texture : GL.Objects.Textures.Texture_Base'Class; Binding : Natural) with Pre => Texture.Kind = Object.Kind; ----------------------------------------------------------------------------- type Uniform_Subroutine (<>) is tagged limited private; function Is_Compatible (Object : Uniform_Subroutine; Index : Subroutine_Index) return Boolean; -- Return True if the index is a compatible subroutine function -- for the subroutine uniform, False otherwise procedure Set_Function (Object : Uniform_Subroutine; Name : String) with Inline; -- Select the given subroutine function to be used by the -- subroutine uniform -- -- This procedure is a shortcut for Set_Function (Index (Name)). procedure Set_Function (Object : Uniform_Subroutine; Index : Subroutine_Index) with Pre => Object.Is_Compatible (Index); -- Select the given subroutine function to be used by the -- subroutine uniform function Index (Object : Uniform_Subroutine; Name : String) return Subroutine_Index; -- Return the index of the subroutine function identified -- by the given name ----------------------------------------------------------------------------- type Uniform_Block is tagged private; ----------------------------------------------------------------------------- function Create_Uniform_Sampler (Object : Program; Name : String) return Uniform_Sampler; function Create_Uniform_Image (Object : Program; Name : String) return Uniform_Image; function Create_Uniform_Subroutine (Object : in out Program; Shader : GL.Objects.Shaders.Shader_Type; Name : String) return Uniform_Subroutine; function Create_Uniform_Block (Object : Program; Name : String) return Uniform_Block; function Create_Uniform_Variable (Object : Program; Name : String) return Uniform; Uniform_Inactive_Error : exception renames GL.Objects.Programs.Uniform_Inactive_Error; Uniform_Type_Error : exception; private type Uniform (Kind : LE.Resource_Type) is tagged record GL_Uniform : GL.Objects.Programs.Uniforms.Uniform; end record; type Uniform_Sampler (Kind : LE.Texture_Kind) is tagged record GL_Uniform : GL.Objects.Programs.Uniforms.Uniform; end record; type Uniform_Image (Kind : LE.Texture_Kind) is tagged record GL_Uniform : GL.Objects.Programs.Uniforms.Uniform; end record; package Indices_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Objects.Programs.Subroutine_Index_Array, "=" => GL.Objects.Programs."="); type Uniform_Subroutine (Program : access Programs.Program) is tagged limited record Location : Uniform_Location; Indices : Indices_Holder.Holder; Shader : GL.Objects.Shaders.Shader_Type; end record; type Uniform_Block is tagged record GL_Uniform : GL.Objects.Programs.Uniforms.Uniform; end record; end Orka.Rendering.Programs.Uniforms;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Containers.Indefinite_Holders; with GL.Low_Level.Enums; with GL.Objects.Programs.Uniforms; with GL.Objects.Textures; with GL.Types; with Orka.Transforms.Singles.Matrices; with Orka.Transforms.Doubles.Matrices; package Orka.Rendering.Programs.Uniforms is pragma Preelaborate; package LE renames GL.Low_Level.Enums; use type LE.Texture_Kind; use type LE.Resource_Type; package TS renames Transforms.Singles.Matrices; package TD renames Transforms.Doubles.Matrices; type Uniform (Kind : LE.Resource_Type) is tagged private; procedure Set_Matrix (Object : Uniform; Value : TS.Matrix4); procedure Set_Matrix (Object : Uniform; Value : TD.Matrix4); procedure Set_Vector (Object : Uniform; Value : TS.Vector4); procedure Set_Vector (Object : Uniform; Value : TD.Vector4); procedure Set_Single (Object : Uniform; Value : GL.Types.Single); procedure Set_Double (Object : Uniform; Value : GL.Types.Double); procedure Set_Int (Object : Uniform; Value : GL.Types.Int); procedure Set_UInt (Object : Uniform; Value : GL.Types.UInt); procedure Set_Boolean (Object : Uniform; Value : Boolean); function GL_Uniform (Object : Uniform) return GL.Objects.Programs.Uniforms.Uniform with Inline; ----------------------------------------------------------------------------- type Uniform_Sampler (Kind : LE.Texture_Kind) is tagged private; procedure Set_Texture (Object : Uniform_Sampler; Texture : GL.Objects.Textures.Texture_Base'Class; Binding : Natural) with Pre => Texture.Kind = Object.Kind or else raise Constraint_Error with "Cannot bind " & Texture.Kind'Image & " to " & Object.Kind'Image & " sampler"; -- TODO Add pre condition to check Texture.Format matches Sampler_Kind -- (see https://www.khronos.org/opengl/wiki/Sampler_(GLSL)#Sampler_types) -- Set the binding point of the uniform sampler and bind the -- given texture to the corresponding texture unit ----------------------------------------------------------------------------- type Uniform_Image (Kind : LE.Texture_Kind) is tagged private; procedure Set_Image (Object : Uniform_Image; Texture : GL.Objects.Textures.Texture_Base'Class; Binding : Natural) with Pre => Texture.Kind = Object.Kind or else raise Constraint_Error with "Cannot bind " & Texture.Kind'Image & " to " & Object.Kind'Image & " image sampler"; ----------------------------------------------------------------------------- type Uniform_Subroutine (<>) is tagged limited private; function Is_Compatible (Object : Uniform_Subroutine; Index : Subroutine_Index) return Boolean; -- Return True if the index is a compatible subroutine function -- for the subroutine uniform, False otherwise procedure Set_Function (Object : Uniform_Subroutine; Name : String) with Inline; -- Select the given subroutine function to be used by the -- subroutine uniform -- -- This procedure is a shortcut for Set_Function (Index (Name)). procedure Set_Function (Object : Uniform_Subroutine; Index : Subroutine_Index) with Pre => Object.Is_Compatible (Index); -- Select the given subroutine function to be used by the -- subroutine uniform function Index (Object : Uniform_Subroutine; Name : String) return Subroutine_Index; -- Return the index of the subroutine function identified -- by the given name ----------------------------------------------------------------------------- type Uniform_Block is tagged private; ----------------------------------------------------------------------------- function Create_Uniform_Sampler (Object : Program; Name : String) return Uniform_Sampler; function Create_Uniform_Image (Object : Program; Name : String) return Uniform_Image; function Create_Uniform_Subroutine (Object : in out Program; Shader : GL.Objects.Shaders.Shader_Type; Name : String) return Uniform_Subroutine; function Create_Uniform_Block (Object : Program; Name : String) return Uniform_Block; function Create_Uniform_Variable (Object : Program; Name : String) return Uniform; Uniform_Inactive_Error : exception renames GL.Objects.Programs.Uniform_Inactive_Error; Uniform_Type_Error : exception; private type Uniform (Kind : LE.Resource_Type) is tagged record GL_Uniform : GL.Objects.Programs.Uniforms.Uniform; end record; type Uniform_Sampler (Kind : LE.Texture_Kind) is tagged record GL_Uniform : GL.Objects.Programs.Uniforms.Uniform; end record; type Uniform_Image (Kind : LE.Texture_Kind) is tagged record GL_Uniform : GL.Objects.Programs.Uniforms.Uniform; end record; package Indices_Holder is new Ada.Containers.Indefinite_Holders (Element_Type => GL.Objects.Programs.Subroutine_Index_Array, "=" => GL.Objects.Programs."="); type Uniform_Subroutine (Program : access Programs.Program) is tagged limited record Location : Uniform_Location; Indices : Indices_Holder.Holder; Shader : GL.Objects.Shaders.Shader_Type; end record; type Uniform_Block is tagged record GL_Uniform : GL.Objects.Programs.Uniforms.Uniform; end record; end Orka.Rendering.Programs.Uniforms;
Add exception message to some pre conditions in package Uniforms
orka: Add exception message to some pre conditions in package Uniforms Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
2c5585d2d25a5e7c9bc45a74baed7e6e06532007
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- 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 Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; T.Fail ("Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use type ADO.Sessions.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (DB.Get_Status = ADO.Sessions.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Nullable_String; begin Name.Is_Null := False; for I in 1 .. 127 loop Append (Name.Value, Character'Val (I)); end loop; Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name.Value), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); declare Content : Ada.Streams.Stream_Element_Array (1 .. 10); Img3 : Regtests.Images.Model.Image_Ref; begin for I in Content'Range loop Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30); end loop; Data := ADO.Create_Blob (Content); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)"); T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small"); DB.Begin_Transaction; Img3.Set_Image (Data); Img3.Set_Create_Date (Ada.Calendar.Clock); Img3.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img3.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); Img2.Set_Image (ADO.Null_Blob); Img2.Save (DB); DB.Commit; end; end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- 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 Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; T.Fail ("Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.Session_Error => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.Session_Error => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use type ADO.Sessions.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (DB.Get_Status = ADO.Sessions.OPEN, "The database connection is open"); Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Nullable_String; begin Name.Is_Null := False; for I in 1 .. 127 loop Append (Name.Value, Character'Val (I)); end loop; Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name.Value), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); declare Content : Ada.Streams.Stream_Element_Array (1 .. 10); Img3 : Regtests.Images.Model.Image_Ref; begin for I in Content'Range loop Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30); end loop; Data := ADO.Create_Blob (Content); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)"); T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small"); DB.Begin_Transaction; Img3.Set_Image (Data); Img3.Set_Create_Date (Ada.Calendar.Clock); Img3.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img3.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); Img2.Set_Image (ADO.Null_Blob); Img2.Save (DB); DB.Commit; end; end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
Change NOT_OPEN exception into Session_Error
Change NOT_OPEN exception into Session_Error
Ada
apache-2.0
stcarrez/ada-ado
92a04ed8308840bf401ca080148d16dcbbf724c6
t0048.adb
t0048.adb
-- t0048.adb - Thu Feb 20 16:54:37 2014 -- -- (c) Warren W. Gay VE3WWG [email protected] -- -- $Id$ -- -- Protected under the GNU GENERAL PUBLIC LICENSE v2, June 1991 with Ada.Text_IO; with Posix; use Posix; procedure T0048 is use Ada.Text_IO; Connect_Addr : constant String := "127.0.0.1"; Inet_C_Addr : s_sockaddr_in; Port_C_No : constant ushort_t := 19199; S, L : fd_t := -1; -- Connecting socket Child : pid_t := -1; Error : errno_t; begin Put_Line("Test 0048 - IPv4 socket/connect/etc."); Fork(Child,Error); pragma Assert(Error = 0); if Child /= 0 then -- Parent process -- Create socket: Socket(PF_INET,SOCK_STREAM,0,S,Error); pragma Assert(Error = 0); pragma Assert(S >= 0); -- Create address to connect with: Inet_C_Addr.sin_family := AF_INET; Inet_C_Addr.sin_port := Htons(Port_C_No); Inet_Aton(Connect_Addr,Inet_C_Addr.sin_addr,Error); pragma Assert(Error = 0); -- Test Inet_Ntop -- should return same IPv4 String declare Str_Addr : String(1..300); Last : Natural := 0; begin Inet_Ntop(Inet_C_Addr.sin_addr,Str_Addr,Last,Error); pragma Assert(Error = 0); pragma Assert(Str_Addr(1..Last) = Connect_Addr); end; -- Test port declare Test_Port : constant ushort_t := Ntohs(Inet_C_Addr.sin_port); begin pragma Assert(Test_Port = Port_C_No); null; end; -- Wait for client to setup and listen Sleep(2); -- Connect to the client process Connect(S,To_Sock_Addr(Inet_C_Addr),Error); pragma Assert(Error = 0); -- Close the socket Close(S,Error); pragma Assert(Error = 0); -- Wait for child process to exit declare Status : int_t := -1; begin Wait_Pid(Child,0,Status,Error); pragma Assert(WIFEXITED(Status)); pragma Assert(WEXITSTATUS(Status) = 0); end; Put_Line("Test 0048 Passed."); else -- Child process -- Create a listening socket: Socket(PF_INET,SOCK_STREAM,0,L,Error); pragma Assert(Error = 0); pragma Assert(L >= 0); -- Create the address to bind to: Inet_C_Addr.sin_family := AF_INET; Inet_C_Addr.sin_port := Htons(Port_C_No); Inet_Aton(Connect_Addr,Inet_C_Addr.sin_addr,Error); pragma Assert(Error = 0); -- Bind to the address: Bind(L,To_Sock_Addr(Inet_C_Addr),Error); pragma Assert(Error = 0); loop Listen(L,10,Error); exit when Error = 0; pragma Assert(Error = EINTR); end loop; -- Accept one connect declare Peer : s_sockaddr; begin loop Accept_Connect(L,Peer,S,Error); exit when Error = 0; pragma Assert(Error = EINTR); end loop; pragma Assert(S >= 0); -- Display peer's address declare Peer_Addr : constant s_sockaddr_in := To_Inet_Addr(Peer); Str_Addr : String(1..300); Last : Natural := 0; Port : constant ushort_t := Ntohs(Peer_Addr.sin_port); begin Inet_Ntop(Peer_Addr.sin_addr,Str_Addr,Last,Error); pragma Assert(Error = 0); Put_Line("Received connect from " & Str_Addr(1..Last) & ":" & ushort_t'Image(Port)); end; end; -- Close listening socket Close(L,Error); pragma Assert(Error = 0); -- Test getsockopt(2) declare Sock_Error : int_t := -33; Keep_Alive : int_t := -33; begin Get_Sockopt(S,SOL_SOCKET,SO_ERROR,Sock_Error,Error); pragma Assert(Error = 0); pragma Assert(Sock_Error = 0); Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); pragma Assert(Keep_Alive = 0 or Keep_Alive = 1); if Keep_Alive /= 0 then Keep_Alive := 0; -- Turn it off Set_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); Keep_Alive := -95; Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); pragma Assert(Keep_Alive = 0); else Keep_Alive := 1; -- Turn it on Set_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); Keep_Alive := -95; Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); pragma Assert(Keep_Alive = 1); end if; end; -- Close accepted socket Close(S,Error); pragma Assert(Error = 0); end if; end T0048;
-- t0048.adb - Thu Feb 20 16:54:37 2014 -- -- (c) Warren W. Gay VE3WWG [email protected] -- -- $Id$ -- -- Protected under the GNU GENERAL PUBLIC LICENSE v2, June 1991 with Ada.Text_IO; with Posix; use Posix; procedure T0048 is use Ada.Text_IO; Connect_Addr : constant String := "127.0.0.1"; Inet_C_Addr : s_sockaddr_in; Port_C_No : constant ushort_t := 19199; S, L : fd_t := -1; -- Connecting socket Child : pid_t := -1; Error : errno_t; begin Put_Line("Test 0048 - IPv4 socket/connect/etc."); Fork(Child,Error); pragma Assert(Error = 0); if Child /= 0 then -- Parent process -- Create socket: Socket(PF_INET,SOCK_STREAM,0,S,Error); pragma Assert(Error = 0); pragma Assert(S >= 0); -- Create address to connect with: Inet_C_Addr.sin_family := AF_INET; Inet_C_Addr.sin_port := Htons(Port_C_No); Inet_Aton(Connect_Addr,Inet_C_Addr.sin_addr,Error); pragma Assert(Error = 0); -- Test Inet_Ntop -- should return same IPv4 String declare Str_Addr : String(1..300); Last : Natural := 0; begin Inet_Ntop(Inet_C_Addr.sin_addr,Str_Addr,Last,Error); pragma Assert(Error = 0); pragma Assert(Str_Addr(1..Last) = Connect_Addr); end; -- Test port declare Test_Port : constant ushort_t := Ntohs(Inet_C_Addr.sin_port); begin pragma Assert(Test_Port = Port_C_No); null; end; -- Wait for client to setup and listen Sleep(2); -- Connect to the client process Connect(S,To_Sock_Addr(Inet_C_Addr),Error); pragma Assert(Error = 0); -- Close the socket Close(S,Error); pragma Assert(Error = 0); -- Wait for child process to exit declare Status : int_t := -1; begin Wait_Pid(Child,0,Status,Error); pragma Assert(WIFEXITED(Status)); pragma Assert(WEXITSTATUS(Status) = 0); end; Put_Line("Test 0048 Passed."); else -- Child process -- Create a listening socket: Socket(PF_INET,SOCK_STREAM,0,L,Error); pragma Assert(Error = 0); pragma Assert(L >= 0); -- Create the address to bind to: Inet_C_Addr.sin_family := AF_INET; Inet_C_Addr.sin_port := Htons(Port_C_No); Inet_Aton(Connect_Addr,Inet_C_Addr.sin_addr,Error); pragma Assert(Error = 0); -- Bind to the address: Bind(L,To_Sock_Addr(Inet_C_Addr),Error); pragma Assert(Error = 0); loop Listen(L,10,Error); exit when Error = 0; pragma Assert(Error = EINTR); end loop; -- Accept one connect declare Peer : s_sockaddr; begin loop Accept_Connect(L,Peer,S,Error); exit when Error = 0; pragma Assert(Error = EINTR); end loop; pragma Assert(S >= 0); -- Display peer's address declare Peer_Addr : constant s_sockaddr_in := To_Inet_Addr(Peer); Str_Addr : String(1..300); Last : Natural := 0; Port : constant ushort_t := Ntohs(Peer_Addr.sin_port); begin Inet_Ntop(Peer_Addr.sin_addr,Str_Addr,Last,Error); pragma Assert(Error = 0); Put_Line("Received connect from " & Str_Addr(1..Last) & ":" & ushort_t'Image(Port)); end; end; -- Close listening socket Close(L,Error); pragma Assert(Error = 0); -- Test getsockopt(2) declare Sock_Error : int_t := -33; Keep_Alive : int_t := -33; begin Get_Sockopt(S,SOL_SOCKET,SO_ERROR,Sock_Error,Error); pragma Assert(Error = 0); pragma Assert(Sock_Error = 0); Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); pragma Assert(Keep_Alive >= 0); if Keep_Alive /= 0 then Keep_Alive := 0; -- Turn it off Set_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); Keep_Alive := -95; Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); pragma Assert(Keep_Alive = 0); else Keep_Alive := 1; -- Turn it on Set_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); Keep_Alive := -95; Get_Sockopt(S,SOL_SOCKET,SO_KEEPALIVE,Keep_Alive,Error); pragma Assert(Error = 0); pragma Assert(Keep_Alive /= 0); end if; end; -- Close accepted socket Close(S,Error); pragma Assert(Error = 0); end if; end T0048;
Test is now more flexible-- Darwin uses values > 1
Test is now more flexible-- Darwin uses values > 1
Ada
lgpl-2.1
ve3wwg/adafpx,ve3wwg/adafpx
233b030fe6c6e48276b77d6a35bf0f692b00f325
src/ado-schemas-databases.ads
src/ado-schemas-databases.ads
----------------------------------------------------------------------- -- ado-schemas-databases -- Database creation -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with ADO.Sessions; with ADO.Configs; package ADO.Schemas.Databases is -- Create the database and initialize it with the schema SQL file. procedure Create_Database (Session : in out Sessions.Master_Session; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); end ADO.Schemas.Databases;
----------------------------------------------------------------------- -- ado-schemas-databases -- Database creation -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with ADO.Sessions.Sources; package ADO.Schemas.Databases is -- 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: this is the -- database that must be created and configured. The `Schema_Path` is the path -- of the SQL file that can be used to populate the database with the schema. -- The `Messages` vector will contain the messages produced during the setup and -- configuration of the database. -- -- For the `sqlite` driver, the `Admin` parameter is not used. procedure Create_Database (Admin : in ADO.Sessions.Sources.Data_Source'Class; Config : in ADO.Sessions.Sources.Data_Source'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); end ADO.Schemas.Databases;
Update the Create_Database to use a Data_Source as configuration parameters
Update the Create_Database to use a Data_Source as configuration parameters
Ada
apache-2.0
stcarrez/ada-ado
d05b4511bd99964881e3c6a9a05ebd738f4bdf91
src/el-expressions.adb
src/el-expressions.adb
----------------------------------------------------------------------- -- EL.Expressions -- Expression Language -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions.Nodes; with EL.Expressions.Parser; with Util.Concurrent.Counters; package body EL.Expressions is -- ------------------------------ -- Check whether the expression is a holds a constant value. -- ------------------------------ function Is_Constant (Expr : Expression'Class) return Boolean is begin return Expr.Node = null; end Is_Constant; -- ------------------------------ -- Get the value of the expression using the given expression context. -- ------------------------------ function Get_Value (Expr : Expression; Context : ELContext'Class) return Object is begin if Expr.Node = null then return Expr.Value; end if; return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context); end Get_Value; -- ------------------------------ -- Get the value of the expression using the given expression context. -- ------------------------------ function Get_Value (Expr : ValueExpression; Context : ELContext'Class) return Object is begin if Expr.Bean = null then if Expr.Node = null then return Expr.Value; else return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context); end if; end if; return To_Object (Expr.Bean); end Get_Value; -- ------------------------------ -- Set the value of the expression to the given object value. -- ------------------------------ procedure Set_Value (Expr : in out ValueExpression; Context : in ELContext'Class; Value : in Object) is begin Expr.Value := Value; end Set_Value; -- ------------------------------ -- Returns true if the expression is read-only. -- ------------------------------ function Is_Readonly (Expr : in ValueExpression) return Boolean is begin if Expr.Bean = null then return True; end if; return not (Expr.Bean.all in EL.Beans.Bean'Class); end Is_Readonly; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- ------------------------------ function Create_Expression (Expr : String; Context : ELContext'Class) return Expression is use EL.Expressions.Nodes; Result : Expression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); if Node /= null then Result.Node := Node.all'Access; end if; return Result; end Create_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ function Reduce_Expression (Expr : Expression; Context : ELContext'Class) return Expression is use EL.Expressions.Nodes; use Ada.Finalization; begin if Expr.Node = null then return Expr; end if; declare Result : constant Reduction := Expr.Node.Reduce (Context); begin return Expression '(Controlled with Node => Result.Node, Value => Result.Value); end; end Reduce_Expression; function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class) return ValueExpression is Result : ValueExpression; begin Result.Bean := Bean; return Result; end Create_ValueExpression; function Create_ValueExpression (Bean : EL.Objects.Object) return ValueExpression is Result : ValueExpression; begin Result.Value := Bean; return Result; end Create_ValueExpression; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- ------------------------------ function Create_Expression (Expr : String; Context : ELContext'Class) return ValueExpression is Result : ValueExpression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); Result.Node := Node.all'Access; return Result; end Create_Expression; overriding function Reduce_Expression (Expr : ValueExpression; Context : ELContext'Class) return ValueExpression is pragma Unreferenced (Context); begin return Expr; end Reduce_Expression; procedure Adjust (Object : in out Expression) is begin if Object.Node /= null then Util.Concurrent.Counters.Increment (Object.Node.Ref_Counter); end if; end Adjust; procedure Finalize (Object : in out Expression) is Node : EL.Expressions.Nodes.ELNode_Access; Is_Zero : Boolean; begin if Object.Node /= null then Node := Object.Node.all'Access; Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Is_Zero); if Is_Zero then EL.Expressions.Nodes.Delete (Node); Object.Node := null; end if; end if; end Finalize; -- ------------------------------ -- Evaluate the method expression and return the object and method -- binding to execute the method. The result contains a pointer -- to the bean object and a method binding. The method binding -- contains the information to invoke the method -- (such as an access to the function or procedure). -- Raises the <b>Invalid_Method</b> exception if the method -- cannot be resolved. -- ------------------------------ function Get_Method_Info (Expr : Method_Expression; Context : ELContext'Class) return Method_Info is use EL.Expressions.Nodes; begin if Expr.Node = null then raise Invalid_Expression with "Method expression is empty"; end if; declare Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access; begin return Node.Get_Method_Info (Context); end; end Get_Method_Info; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- The context is used to resolve the functions. Variables will be -- resolved during evaluation of the expression. -- Raises <b>Invalid_Expression</b> if the expression is invalid. -- ------------------------------ overriding function Create_Expression (Expr : String; Context : EL.Contexts.ELContext'Class) return Method_Expression is use type EL.Expressions.Nodes.ELNode_Access; Result : Method_Expression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); -- The root of the method expression must be an ELValue node. if Node = null or else not (Node.all in Nodes.ELValue'Class) then raise Invalid_Expression with "Expression is not a method expression"; end if; Result.Node := Node.all'Access; return Result; end Create_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ overriding function Reduce_Expression (Expr : Method_Expression; Context : EL.Contexts.ELContext'Class) return Method_Expression is pragma Unreferenced (Context); begin return Expr; end Reduce_Expression; end EL.Expressions;
----------------------------------------------------------------------- -- EL.Expressions -- Expression Language -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions.Nodes; with EL.Expressions.Parser; with Util.Concurrent.Counters; package body EL.Expressions is -- ------------------------------ -- Check whether the expression is a holds a constant value. -- ------------------------------ function Is_Constant (Expr : Expression'Class) return Boolean is begin return Expr.Node = null; end Is_Constant; -- ------------------------------ -- Get the value of the expression using the given expression context. -- ------------------------------ function Get_Value (Expr : Expression; Context : ELContext'Class) return Object is begin if Expr.Node = null then return Expr.Value; end if; return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context); end Get_Value; -- ------------------------------ -- Get the value of the expression using the given expression context. -- ------------------------------ function Get_Value (Expr : ValueExpression; Context : ELContext'Class) return Object is begin if Expr.Bean = null then if Expr.Node = null then return Expr.Value; else return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context); end if; end if; return To_Object (Expr.Bean); end Get_Value; -- ------------------------------ -- Set the value of the expression to the given object value. -- ------------------------------ procedure Set_Value (Expr : in out ValueExpression; Context : in ELContext'Class; Value : in Object) is begin Expr.Value := Value; end Set_Value; -- ------------------------------ -- Returns true if the expression is read-only. -- ------------------------------ function Is_Readonly (Expr : in ValueExpression) return Boolean is begin if Expr.Bean = null then return True; end if; return not (Expr.Bean.all in EL.Beans.Bean'Class); end Is_Readonly; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- ------------------------------ function Create_Expression (Expr : String; Context : ELContext'Class) return Expression is use EL.Expressions.Nodes; Result : Expression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); if Node /= null then Result.Node := Node.all'Access; end if; return Result; end Create_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ function Reduce_Expression (Expr : Expression; Context : ELContext'Class) return Expression is use EL.Expressions.Nodes; use Ada.Finalization; begin if Expr.Node = null then return Expr; end if; declare Result : constant Reduction := Expr.Node.Reduce (Context); begin return Expression '(Controlled with Node => Result.Node, Value => Result.Value); end; end Reduce_Expression; function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class) return ValueExpression is Result : ValueExpression; begin Result.Bean := Bean; return Result; end Create_ValueExpression; function Create_ValueExpression (Bean : EL.Objects.Object) return ValueExpression is Result : ValueExpression; begin Result.Value := Bean; return Result; end Create_ValueExpression; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- ------------------------------ function Create_Expression (Expr : String; Context : ELContext'Class) return ValueExpression is Result : ValueExpression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); Result.Node := Node.all'Access; return Result; end Create_Expression; overriding function Reduce_Expression (Expr : ValueExpression; Context : ELContext'Class) return ValueExpression is pragma Unreferenced (Context); begin return Expr; end Reduce_Expression; procedure Adjust (Object : in out Expression) is begin if Object.Node /= null then Util.Concurrent.Counters.Increment (Object.Node.Ref_Counter); end if; end Adjust; procedure Finalize (Object : in out Expression) is Node : EL.Expressions.Nodes.ELNode_Access; Is_Zero : Boolean; begin if Object.Node /= null then Node := Object.Node.all'Access; Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Is_Zero); if Is_Zero then EL.Expressions.Nodes.Delete (Node); Object.Node := null; end if; end if; end Finalize; -- ------------------------------ -- Evaluate the method expression and return the object and method -- binding to execute the method. The result contains a pointer -- to the bean object and a method binding. The method binding -- contains the information to invoke the method -- (such as an access to the function or procedure). -- Raises the <b>Invalid_Method</b> exception if the method -- cannot be resolved. -- ------------------------------ function Get_Method_Info (Expr : Method_Expression; Context : ELContext'Class) return Method_Info is use EL.Expressions.Nodes; begin if Expr.Node = null then raise Invalid_Expression with "Method expression is empty"; end if; declare Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access; begin return Node.Get_Method_Info (Context); end; end Get_Method_Info; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- The context is used to resolve the functions. Variables will be -- resolved during evaluation of the expression. -- Raises <b>Invalid_Expression</b> if the expression is invalid. -- ------------------------------ overriding function Create_Expression (Expr : String; Context : EL.Contexts.ELContext'Class) return Method_Expression is use type EL.Expressions.Nodes.ELNode_Access; Result : Method_Expression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); -- The root of the method expression must be an ELValue node. if Node = null or else not (Node.all in Nodes.ELValue'Class) then EL.Expressions.Nodes.Delete (Node); raise Invalid_Expression with "Expression is not a method expression"; end if; Result.Node := Node.all'Access; return Result; end Create_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ overriding function Reduce_Expression (Expr : Method_Expression; Context : EL.Contexts.ELContext'Class) return Method_Expression is pragma Unreferenced (Context); begin return Expr; end Reduce_Expression; end EL.Expressions;
Fix memory leak if the method expression is a valid EL expression but not a method expression
Fix memory leak if the method expression is a valid EL expression but not a method expression
Ada
apache-2.0
Letractively/ada-el
4f3bc7c31a40cdb12961b62422d70c1d333e8bb3
src/asf-lifecycles.adb
src/asf-lifecycles.adb
----------------------------------------------------------------------- -- asf-lifecycles -- Lifecycle -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body ASF.Lifecycles is -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Controller : in out Lifecycle; App : access ASF.Applications.Main.Application'Class) is begin -- Create the phase controllers. Lifecycle'Class (Controller).Create_Phase_Controllers; -- Initialize the phase controllers. for Phase in Controller.Controllers'Range loop Controller.Controllers (Phase).Initialize (App); end loop; end Initialize; -- ------------------------------ -- Finalize the lifecycle handler, freeing the allocated storage. -- ------------------------------ overriding procedure Finalize (Controller : in out Lifecycle) is procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class, Phase_Controller_Access); begin -- Free the phase controllers. for Phase in Controller.Controllers'Range loop Free (Controller.Controllers (Phase)); end loop; end Finalize; -- ------------------------------ -- Set the controller to be used for the given phase. -- ------------------------------ procedure Set_Controller (Controller : in out Lifecycle; Phase : in Phase_Type; Instance : in Phase_Controller_Access) is begin Controller.Controllers (Phase) := Instance; end Set_Controller; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop if Context.Get_Render_Response or Context.Get_Response_Completed then return; end if; Controller.Controllers (Phase).Execute (Context); end loop; end Execute; -- ------------------------------ -- Render the response by executing the response phase. -- ------------------------------ procedure Render (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin Controller.Controllers (RENDER_RESPONSE).Execute (Context); end Render; end ASF.Lifecycles;
----------------------------------------------------------------------- -- asf-lifecycles -- Lifecycle -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Contexts.Exceptions; package body ASF.Lifecycles is -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Controller : in out Lifecycle; App : access ASF.Applications.Main.Application'Class) is begin -- Create the phase controllers. Lifecycle'Class (Controller).Create_Phase_Controllers; -- Initialize the phase controllers. for Phase in Controller.Controllers'Range loop Controller.Controllers (Phase).Initialize (App); end loop; end Initialize; -- ------------------------------ -- Finalize the lifecycle handler, freeing the allocated storage. -- ------------------------------ overriding procedure Finalize (Controller : in out Lifecycle) is procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class, Phase_Controller_Access); begin -- Free the phase controllers. for Phase in Controller.Controllers'Range loop Free (Controller.Controllers (Phase)); end loop; end Finalize; -- ------------------------------ -- Set the controller to be used for the given phase. -- ------------------------------ procedure Set_Controller (Controller : in out Lifecycle; Phase : in Phase_Type; Instance : in Phase_Controller_Access) is begin Controller.Controllers (Phase) := Instance; end Set_Controller; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Contexts.Exceptions.Exception_Handler_Access; begin for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop if Context.Get_Render_Response or Context.Get_Response_Completed then return; end if; begin Controller.Controllers (Phase).Execute (Context); exception when E : others => Context.Queue_Exception (E); end; -- If exceptions have been raised and queued during the current phase, process them. -- An exception handler could use them to redirect the current request to another -- page or navigate to a specific view. declare Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access := Context.Get_Exception_Handler; begin if Ex /= null then Ex.Handle; end if; end; end loop; end Execute; -- ------------------------------ -- Render the response by executing the response phase. -- ------------------------------ procedure Render (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin Controller.Controllers (RENDER_RESPONSE).Execute (Context); end Render; end ASF.Lifecycles;
Use the Exception handler - Invoke the exception handler if an ASF phase has raised/queued some exception
Use the Exception handler - Invoke the exception handler if an ASF phase has raised/queued some exception
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
66e4569ceab38eac4e844ea8206918b06b8399a7
src/wiki-documents.ads
src/wiki-documents.ads
----------------------------------------------------------------------- -- wiki-documents -- Wiki document -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Wiki.Attributes; with Wiki.Nodes; -- === Documents === -- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser -- with one of the supported syntax. package Wiki.Documents is pragma Preelaborate; -- ------------------------------ -- A Wiki Document -- ------------------------------ type Document is tagged private; -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List); -- Pop the HTML tag. procedure Pop_Node (From : in out Document; Tag : in Html_Tag); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Into : in out Document; Level : in Natural); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Wiki.Nodes.Node_Type)); -- Get the table of content node associated with the document. procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref); -- Get the table of content node associated with the document. function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref; private -- Append a node to the document. procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access); type Document is tagged record Nodes : Wiki.Nodes.Node_List_Ref; TOC : Wiki.Nodes.Node_List_Ref; Current : Wiki.Nodes.Node_Type_Access; end record; end Wiki.Documents;
----------------------------------------------------------------------- -- wiki-documents -- Wiki document -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Wiki.Attributes; with Wiki.Nodes; -- === Documents === -- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser -- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts: -- -- * A main document body that represents the Wiki content that was parsed. -- * A table of contents part that was built while Wiki sections are collected. -- -- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to -- be used by the wiki parser and filters to build the document. The document is made of -- nodes whose knowledge is required by the renderer. -- -- A document instance must be declared before parsing a text: -- -- Doc : Wiki.Documents.Document; package Wiki.Documents is pragma Preelaborate; -- ------------------------------ -- A Wiki Document -- ------------------------------ type Document is tagged private; -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. procedure Append (Into : in out Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Append a HTML tag start node to the document. procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List); -- Pop the HTML tag. procedure Pop_Node (From : in out Document; Tag : in Html_Tag); -- Append the text with the given format at end of the document. procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map); -- Append a section header at end of the document. procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive); -- Add a link. procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add an image. procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a quote. procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Into : in out Document; Level : in Positive; Ordered : in Boolean); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Into : in out Document; Level : in Natural); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Wiki.Nodes.Node_Type)); -- Get the table of content node associated with the document. procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref); -- Get the table of content node associated with the document. function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref; private -- Append a node to the document. procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access); type Document is tagged record Nodes : Wiki.Nodes.Node_List_Ref; TOC : Wiki.Nodes.Node_List_Ref; Current : Wiki.Nodes.Node_Type_Access; end record; end Wiki.Documents;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
7be64f2f785152d95574c18bdf5218b0a3c8c730
boards/OpenMV2/openmv-sensor.adb
boards/OpenMV2/openmv-sensor.adb
with STM32.DCMI; with STM32.DMA; use STM32.DMA; with Ada.Real_Time; use Ada.Real_Time; with OV2640; use OV2640; with Interfaces; use Interfaces; with HAL.I2C; use HAL.I2C; with HAL.Bitmap; use HAL.Bitmap; with HAL; use HAL; package body OpenMV.Sensor is package DCMI renames STM32.DCMI; function Probe (Cam_Addr : out UInt10) return Boolean; REG_PID : constant := 16#0A#; -- REG_VER : constant := 16#0B#; CLK_PWM_Mod : PWM_Modulator; Camera : OV2640_Cam (Sensor_I2C'Access); Is_Initialized : Boolean := False; ----------------- -- Initialized -- ----------------- function Initialized return Boolean is (Is_Initialized); ----------- -- Probe -- ----------- function Probe (Cam_Addr : out UInt10) return Boolean is Status : I2C_Status; begin for Addr in UInt10 range 0 .. 126 loop Sensor_I2C.Master_Transmit (Addr => Addr, Data => (0 => 0), Status => Status, Timeout => 10_000); if Status = Ok then Cam_Addr := Addr; return True; end if; end loop; return False; end Probe; ---------------- -- Initialize -- ---------------- procedure Initialize is procedure Initialize_Clock; procedure Initialize_Camera; procedure Initialize_IO; procedure Initialize_DCMI; procedure Initialize_DMA; ---------------------- -- Initialize_Clock -- ---------------------- procedure Initialize_Clock is begin Initialise_PWM_Timer (SENSOR_CLK_TIM, Float (SENSOR_CLK_FREQ)); Attach_PWM_Channel (This => SENSOR_CLK_TIM'Access, Modulator => CLK_PWM_Mod, Channel => SENSOR_CLK_CHAN, Point => SENSOR_CLK_IO, PWM_AF => SENSOR_CLK_AF); Set_Duty_Cycle (This => CLK_PWM_Mod, Value => 50); Enable_PWM (CLK_PWM_Mod); end Initialize_Clock; ----------------------- -- Initialize_Camera -- ----------------------- procedure Initialize_Camera is Cam_Addr : UInt10; Data : I2C_Data (1 .. 1); Status : I2C_Status; PID : HAL.Byte; begin -- Power cycle Set (DCMI_PWDN); delay until Clock + Milliseconds (10); Clear (DCMI_PWDN); delay until Clock + Milliseconds (10); Initialize_Clock; Set (DCMI_RST); delay until Clock + Milliseconds (10); Clear (DCMI_RST); delay until Clock + Milliseconds (10); if not Probe (Cam_Addr) then -- Retry with reversed reset polarity Clear (DCMI_RST); delay until Clock + Milliseconds (10); Set (DCMI_RST); delay until Clock + Milliseconds (10); if not Probe (Cam_Addr) then raise Program_Error; end if; end if; -- Select sensor bank Sensor_I2C.Mem_Write (Addr => Cam_Addr, Mem_Addr => 16#FF#, Mem_Addr_Size => Memory_Size_8b, Data => (0 => 1), Status => Status); if Status /= Ok then raise Program_Error; end if; Sensor_I2C.Mem_Read (Addr => Cam_Addr, Mem_Addr => REG_PID, Mem_Addr_Size => Memory_Size_8b, Data => Data, Status => Status); if Status /= Ok then raise Program_Error; end if; PID := Data (Data'First); if PID /= OV2640_PID then raise Program_Error; end if; Initialize (Camera, Cam_Addr); Set_Pixel_Format (Camera, Pix_RGB565); Set_Frame_Size (Camera, QQVGA2); end Initialize_Camera; ------------------- -- Initialize_IO -- ------------------- procedure Initialize_IO is GPIO_Conf : GPIO_Port_Configuration; DCMI_AF_Points : constant GPIO_Points := GPIO_Points'(DCMI_D0, DCMI_D1, DCMI_D2, DCMI_D3, DCMI_D4, DCMI_D5, DCMI_D6, DCMI_D7, DCMI_VSYNC, DCMI_HSYNC, DCMI_PCLK); DCMI_Out_Points : constant GPIO_Points := GPIO_Points'(DCMI_PWDN, DCMI_RST, FS_IN); begin Enable_Clock (GPIO_Points'(Sensor_I2C_SCL, Sensor_I2C_SDA)); GPIO_Conf.Speed := Speed_25MHz; GPIO_Conf.Mode := Mode_AF; GPIO_Conf.Output_Type := Open_Drain; GPIO_Conf.Resistors := Floating; Configure_IO (GPIO_Points'(Sensor_I2C_SCL, Sensor_I2C_SDA), GPIO_Conf); Configure_Alternate_Function (Sensor_I2C_SCL, Sensor_I2C_SCL_AF); Configure_Alternate_Function (Sensor_I2C_SDA, Sensor_I2C_SDA_AF); Enable_Clock (Sensor_I2C); Reset (Sensor_I2C); Enable_Clock (Sensor_I2C); Configure (Sensor_I2C, (Mode => I2C_Mode, Duty_Cycle => DutyCycle_2, Own_Address => 16#00#, Addressing_Mode => Addressing_Mode_7bit, General_Call_Enabled => False, Clock_Stretching_Enabled => True, Clock_Speed => 10_000)); Enable_Clock (DCMI_Out_Points); -- Sensor PowerDown, Reset and FSIN GPIO_Conf.Mode := Mode_Out; GPIO_Conf.Output_Type := Push_Pull; GPIO_Conf.Resistors := Pull_Down; Configure_IO (DCMI_Out_Points, GPIO_Conf); Clear (DCMI_Out_Points); GPIO_Conf.Mode := Mode_AF; GPIO_Conf.Output_Type := Push_Pull; GPIO_Conf.Resistors := Pull_Down; Configure_IO (DCMI_AF_Points, GPIO_Conf); Configure_Alternate_Function (DCMI_AF_Points, GPIO_AF_DCMI); end Initialize_IO; --------------------- -- Initialize_DCMI -- --------------------- procedure Initialize_DCMI is begin Enable_DCMI_Clock; DCMI.Configure (Data_Mode => DCMI.DCMI_8bit, Capture_Rate => DCMI.Capture_All, -- Sensor specific (OV2640) Vertical_Polarity => DCMI.Active_Low, Horizontal_Polarity => DCMI.Active_Low, Pixel_Clock_Polarity => DCMI.Active_High, Hardware_Sync => True, JPEG => False); DCMI.Disable_Crop; DCMI.Enable_DCMI; end Initialize_DCMI; -------------------- -- Initialize_DMA -- -------------------- procedure Initialize_DMA is Config : DMA_Stream_Configuration; begin Enable_Clock (Sensor_DMA); Config.Channel := Sensor_DMA_Chan; Config.Direction := Peripheral_To_Memory; Config.Increment_Peripheral_Address := False; Config.Increment_Memory_Address := True; Config.Peripheral_Data_Format := Words; Config.Memory_Data_Format := Words; Config.Operation_Mode := Normal_Mode; Config.Priority := Priority_High; Config.FIFO_Enabled := True; Config.FIFO_Threshold := FIFO_Threshold_Full_Configuration; Config.Memory_Burst_Size := Memory_Burst_Inc4; Config.Peripheral_Burst_Size := Peripheral_Burst_Single; Configure (Sensor_DMA, Sensor_DMA_Stream, Config); end Initialize_DMA; begin Initialize_IO; Initialize_Camera; Initialize_DCMI; Initialize_DMA; Is_Initialized := True; end Initialize; -------------- -- Snapshot -- -------------- procedure Snapshot (BM : HAL.Bitmap.Bitmap_Buffer'Class) is Status : DMA_Error_Code; begin if BM.Width /= Image_Width or else BM.Height /= Image_Height then raise Program_Error; end if; if not Compatible_Alignments (Sensor_DMA, Sensor_DMA_Stream, DCMI.Data_Register_Address, BM.Addr) then raise Program_Error; end if; Start_Transfer (Unit => Sensor_DMA, Stream => Sensor_DMA_Stream, Source => DCMI.Data_Register_Address, Destination => BM.Addr, Data_Count => Interfaces.Unsigned_16 ((BM.Width * BM.Height) / 2)); DCMI.Start_Capture (DCMI.Snapshot); Poll_For_Completion (Sensor_DMA, Sensor_DMA_Stream, Full_Transfer, Milliseconds (1000), Status); if Status /= DMA_No_Error then Abort_Transfer (Sensor_DMA, Sensor_DMA_Stream, Status); pragma Unreferenced (Status); raise Program_Error; end if; end Snapshot; end OpenMV.Sensor;
with STM32.DCMI; with STM32.DMA; use STM32.DMA; with Ada.Real_Time; use Ada.Real_Time; with OV2640; use OV2640; with Interfaces; use Interfaces; with HAL.I2C; use HAL.I2C; with HAL.Bitmap; use HAL.Bitmap; with HAL; use HAL; package body OpenMV.Sensor is package DCMI renames STM32.DCMI; function Probe (Cam_Addr : out UInt10) return Boolean; REG_PID : constant := 16#0A#; -- REG_VER : constant := 16#0B#; CLK_PWM_Mod : PWM_Modulator; Camera : OV2640_Cam (Sensor_I2C'Access); Is_Initialized : Boolean := False; ----------------- -- Initialized -- ----------------- function Initialized return Boolean is (Is_Initialized); ----------- -- Probe -- ----------- function Probe (Cam_Addr : out UInt10) return Boolean is Status : I2C_Status; begin for Addr in UInt10 range 0 .. 126 loop Sensor_I2C.Master_Transmit (Addr => Addr, Data => (0 => 0), Status => Status, Timeout => 10_000); if Status = Ok then Cam_Addr := Addr; return True; end if; end loop; return False; end Probe; ---------------- -- Initialize -- ---------------- procedure Initialize is procedure Initialize_Clock; procedure Initialize_Camera; procedure Initialize_IO; procedure Initialize_DCMI; procedure Initialize_DMA; ---------------------- -- Initialize_Clock -- ---------------------- procedure Initialize_Clock is begin Initialise_PWM_Timer (SENSOR_CLK_TIM, Float (SENSOR_CLK_FREQ)); Attach_PWM_Channel (This => SENSOR_CLK_TIM'Access, Modulator => CLK_PWM_Mod, Channel => SENSOR_CLK_CHAN, Point => SENSOR_CLK_IO, PWM_AF => SENSOR_CLK_AF); Set_Duty_Cycle (This => CLK_PWM_Mod, Value => 50); Enable_PWM (CLK_PWM_Mod); end Initialize_Clock; ----------------------- -- Initialize_Camera -- ----------------------- procedure Initialize_Camera is Cam_Addr : UInt10; Data : I2C_Data (1 .. 1); Status : I2C_Status; PID : HAL.Byte; begin -- Power cycle Set (DCMI_PWDN); delay until Clock + Milliseconds (10); Clear (DCMI_PWDN); delay until Clock + Milliseconds (10); Initialize_Clock; Set (DCMI_RST); delay until Clock + Milliseconds (10); Clear (DCMI_RST); delay until Clock + Milliseconds (10); if not Probe (Cam_Addr) then -- Retry with reversed reset polarity Clear (DCMI_RST); delay until Clock + Milliseconds (10); Set (DCMI_RST); delay until Clock + Milliseconds (10); if not Probe (Cam_Addr) then raise Program_Error; end if; end if; -- Select sensor bank Sensor_I2C.Mem_Write (Addr => Cam_Addr, Mem_Addr => 16#FF#, Mem_Addr_Size => Memory_Size_8b, Data => (0 => 1), Status => Status); if Status /= Ok then raise Program_Error; end if; Sensor_I2C.Mem_Read (Addr => Cam_Addr, Mem_Addr => REG_PID, Mem_Addr_Size => Memory_Size_8b, Data => Data, Status => Status); if Status /= Ok then raise Program_Error; end if; PID := Data (Data'First); if PID /= OV2640_PID then raise Program_Error; end if; Initialize (Camera, Cam_Addr); Set_Pixel_Format (Camera, Pix_RGB565); Set_Frame_Size (Camera, QQVGA2); end Initialize_Camera; ------------------- -- Initialize_IO -- ------------------- procedure Initialize_IO is GPIO_Conf : GPIO_Port_Configuration; DCMI_AF_Points : constant GPIO_Points := GPIO_Points'(DCMI_D0, DCMI_D1, DCMI_D2, DCMI_D3, DCMI_D4, DCMI_D5, DCMI_D6, DCMI_D7, DCMI_VSYNC, DCMI_HSYNC, DCMI_PCLK); DCMI_Out_Points : GPIO_Points := GPIO_Points'(DCMI_PWDN, DCMI_RST, FS_IN); begin Enable_Clock (GPIO_Points'(Sensor_I2C_SCL, Sensor_I2C_SDA)); GPIO_Conf.Speed := Speed_25MHz; GPIO_Conf.Mode := Mode_AF; GPIO_Conf.Output_Type := Open_Drain; GPIO_Conf.Resistors := Floating; Configure_IO (GPIO_Points'(Sensor_I2C_SCL, Sensor_I2C_SDA), GPIO_Conf); Configure_Alternate_Function (Sensor_I2C_SCL, Sensor_I2C_SCL_AF); Configure_Alternate_Function (Sensor_I2C_SDA, Sensor_I2C_SDA_AF); Enable_Clock (Sensor_I2C); Reset (Sensor_I2C); Enable_Clock (Sensor_I2C); Configure (Sensor_I2C, (Mode => I2C_Mode, Duty_Cycle => DutyCycle_2, Own_Address => 16#00#, Addressing_Mode => Addressing_Mode_7bit, General_Call_Enabled => False, Clock_Stretching_Enabled => True, Clock_Speed => 10_000)); Enable_Clock (DCMI_Out_Points); -- Sensor PowerDown, Reset and FSIN GPIO_Conf.Mode := Mode_Out; GPIO_Conf.Output_Type := Push_Pull; GPIO_Conf.Resistors := Pull_Down; Configure_IO (DCMI_Out_Points, GPIO_Conf); Clear (DCMI_Out_Points); GPIO_Conf.Mode := Mode_AF; GPIO_Conf.Output_Type := Push_Pull; GPIO_Conf.Resistors := Pull_Down; Configure_IO (DCMI_AF_Points, GPIO_Conf); Configure_Alternate_Function (DCMI_AF_Points, GPIO_AF_DCMI); end Initialize_IO; --------------------- -- Initialize_DCMI -- --------------------- procedure Initialize_DCMI is begin Enable_DCMI_Clock; DCMI.Configure (Data_Mode => DCMI.DCMI_8bit, Capture_Rate => DCMI.Capture_All, -- Sensor specific (OV2640) Vertical_Polarity => DCMI.Active_Low, Horizontal_Polarity => DCMI.Active_Low, Pixel_Clock_Polarity => DCMI.Active_High, Hardware_Sync => True, JPEG => False); DCMI.Disable_Crop; DCMI.Enable_DCMI; end Initialize_DCMI; -------------------- -- Initialize_DMA -- -------------------- procedure Initialize_DMA is Config : DMA_Stream_Configuration; begin Enable_Clock (Sensor_DMA); Config.Channel := Sensor_DMA_Chan; Config.Direction := Peripheral_To_Memory; Config.Increment_Peripheral_Address := False; Config.Increment_Memory_Address := True; Config.Peripheral_Data_Format := Words; Config.Memory_Data_Format := Words; Config.Operation_Mode := Normal_Mode; Config.Priority := Priority_High; Config.FIFO_Enabled := True; Config.FIFO_Threshold := FIFO_Threshold_Full_Configuration; Config.Memory_Burst_Size := Memory_Burst_Inc4; Config.Peripheral_Burst_Size := Peripheral_Burst_Single; Configure (Sensor_DMA, Sensor_DMA_Stream, Config); end Initialize_DMA; begin Initialize_IO; Initialize_Camera; Initialize_DCMI; Initialize_DMA; Is_Initialized := True; end Initialize; -------------- -- Snapshot -- -------------- procedure Snapshot (BM : HAL.Bitmap.Bitmap_Buffer'Class) is Status : DMA_Error_Code; begin if BM.Width /= Image_Width or else BM.Height /= Image_Height then raise Program_Error; end if; if not Compatible_Alignments (Sensor_DMA, Sensor_DMA_Stream, DCMI.Data_Register_Address, BM.Addr) then raise Program_Error; end if; Start_Transfer (Unit => Sensor_DMA, Stream => Sensor_DMA_Stream, Source => DCMI.Data_Register_Address, Destination => BM.Addr, Data_Count => Interfaces.Unsigned_16 ((BM.Width * BM.Height) / 2)); DCMI.Start_Capture (DCMI.Snapshot); Poll_For_Completion (Sensor_DMA, Sensor_DMA_Stream, Full_Transfer, Milliseconds (1000), Status); if Status /= DMA_No_Error then Abort_Transfer (Sensor_DMA, Sensor_DMA_Stream, Status); pragma Unreferenced (Status); raise Program_Error; end if; end Snapshot; end OpenMV.Sensor;
Fix erroneous constant GPIO
OpenMV: Fix erroneous constant GPIO
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
bf4e925955bc9fa7486e3211c2330072d95a7322
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 : 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"); -- Storing a date in the database will loose some precision. T.Assert (S1.Get_Start_Date.Value >= T1 - 1.0, "Start date is invalid 1"); T.Assert (S1.Get_Start_Date.Value >= T2 - 1.0, "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;
----------------------------------------------------------------------- -- 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"); -- Storing a date in the database will loose some precision. T.Assert (S1.Get_Start_Date.Value >= T1 - 1.0, "Start date is invalid 1"); 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 unit test execution due to date issues
Fix unit test execution due to date issues
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5c338bcb531a3712594fc55b80404882594b7966
regtests/asf-lifecycles-tests.adb
regtests/asf-lifecycles-tests.adb
----------------------------------------------------------------------- -- asf-lifecycles-tests - Tests for ASF lifecycles -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Test_Caller; with Util.Beans.Objects; with ASF.Tests; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Applications.Main; with ASF.Applications.Tests; package body ASF.Lifecycles.Tests is use Util.Beans.Objects; use ASF.Tests; package Caller is new Util.Test_Caller (Test, "Lifecycles"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test lifecycle (get)", Test_Get_Lifecycle'Access); Caller.Add_Test (Suite, "Test lifecycle (postback)", Test_Post_Lifecycle'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); use type ASF.Applications.Main.Application_Access; Fact : ASF.Applications.Main.Application_Factory; begin if ASF.Tests.Get_Application = null then ASF.Tests.Initialize (Util.Tests.Get_Properties, Factory => Fact); end if; end Set_Up; -- ------------------------------ -- Test a GET request and the lifecycles that this implies. -- ------------------------------ procedure Test_Get_Lifecycle (T : in out Test) is use ASF.Events.Phases; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased ASF.Applications.Tests.Form_Bean; Listener : aliased Test_Phase_Listener; Handler : constant Lifecycle_Access := ASF.Tests.Get_Application.Get_Lifecycle_Handler; begin Handler.Add_Phase_Listener (Listener'Unchecked_Access); Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt"); Listener.Check_Get_Counters (T, 1); Listener.Check_Post_Counters (T, 0); Handler.Remove_Phase_Listener (Listener'Unchecked_Access); exception when others => Handler.Remove_Phase_Listener (Listener'Unchecked_Access); raise; end Test_Get_Lifecycle; -- ------------------------------ -- Test a GET+POST request with submitted values and an action method called on the bean. -- ------------------------------ procedure Test_Post_Lifecycle (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased ASF.Applications.Tests.Form_Bean; Listener : aliased Test_Phase_Listener; Handler : constant Lifecycle_Access := ASF.Tests.Get_Application.Get_Lifecycle_Handler; begin Handler.Add_Phase_Listener (Listener'Unchecked_Access); Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt"); Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12345"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("ok", "1"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post.txt"); Listener.Check_Post_Counters (T, 1); Listener.Check_Get_Counters (T, 2); Handler.Remove_Phase_Listener (Listener'Unchecked_Access); exception when others => Handler.Remove_Phase_Listener (Listener'Unchecked_Access); raise; end Test_Post_Lifecycle; -- ------------------------------ -- Check that the RESTORE_VIEW and RENDER_RESPONSE counters have the given value. -- ------------------------------ procedure Check_Get_Counters (Listener : in Test_Phase_Listener; T : in out Test'Class; Value : in Natural) is use ASF.Events.Phases; begin Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (RESTORE_VIEW), "Invalid before RESTORE_VIEW count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (RESTORE_VIEW), "Invalid after RESTORE_VIEW count"); Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (RENDER_RESPONSE), "Invalid before RENDER_RESPONSE count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (RENDER_RESPONSE), "Invalid after RENDER_RESPONSE count"); end Check_Get_Counters; -- ------------------------------ -- Check that the APPLY_REQUESTS .. INVOKE_APPLICATION counters have the given value. -- ------------------------------ procedure Check_Post_Counters (Listener : in Test_Phase_Listener; T : in out Test'Class; Value : in Natural) is use ASF.Events.Phases; begin Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (APPLY_REQUEST_VALUES), "Invalid before APPLY_REQUEST_VALUES count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (APPLY_REQUEST_VALUES), "Invalid after APPLY_REQUEST_VALUES count"); Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (PROCESS_VALIDATION), "Invalid before PROCESS_VALIDATION count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (PROCESS_VALIDATION), "Invalid after PROCESS_VALIDATION count"); Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (UPDATE_MODEL_VALUES), "Invalid before UPDATE_MODEL_VALUES count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (UPDATE_MODEL_VALUES), "Invalid after UPDATE_MODEL_VALUES count"); Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (INVOKE_APPLICATION), "Invalid before INVOKE_APPLICATION count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (INVOKE_APPLICATION), "Invalid after INVOKE_APPLICATION count"); end Check_Post_Counters; -- ------------------------------ -- Notifies that the lifecycle phase described by the event is about to begin. -- ------------------------------ procedure Before_Phase (Listener : in Test_Phase_Listener; Event : in ASF.Events.Phases.Phase_Event'Class) is begin Listener.Before_Count (Event.Phase) := Listener.Before_Count (Event.Phase) + 1; end Before_Phase; -- ------------------------------ -- Notifies that the lifecycle phase described by the event has finished. -- ------------------------------ procedure After_Phase (Listener : in Test_Phase_Listener; Event : in ASF.Events.Phases.Phase_Event'Class) is begin Listener.After_Count (Event.Phase) := Listener.After_Count (Event.Phase) + 1; end After_Phase; -- ------------------------------ -- Return the phase that this listener is interested in processing the <b>Phase_Event</b> -- events. If the listener is interested by several events, it should return <b>ANY_PHASE</b>. -- ------------------------------ function Get_Phase (Listener : in Test_Phase_Listener) return ASF.Events.Phases.Phase_Type is begin return Listener.Phase; end Get_Phase; overriding procedure Initialize (Listener : in out Test_Phase_Listener) is begin Listener.After_Count := new Phase_Counters '(others => 0); Listener.Before_Count := new Phase_Counters '(others => 0); end Initialize; overriding procedure Finalize (Listener : in out Test_Phase_Listener) is procedure Free is new Ada.Unchecked_Deallocation (Object => Phase_Counters, Name => Phase_Counters_Array); begin Free (Listener.After_Count); Free (Listener.Before_Count); end Finalize; end ASF.Lifecycles.Tests;
----------------------------------------------------------------------- -- asf-lifecycles-tests - Tests for ASF lifecycles -- Copyright (C) 2012, 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 Util.Test_Caller; with Util.Beans.Objects; with ASF.Tests; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Applications.Main; with ASF.Applications.Tests; package body ASF.Lifecycles.Tests is use Util.Beans.Objects; use ASF.Tests; package Caller is new Util.Test_Caller (Test, "Lifecycles"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test lifecycle (get)", Test_Get_Lifecycle'Access); Caller.Add_Test (Suite, "Test lifecycle (postback)", Test_Post_Lifecycle'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); use type ASF.Applications.Main.Application_Access; Fact : ASF.Applications.Main.Application_Factory; begin if ASF.Tests.Get_Application = null then ASF.Tests.Initialize (Util.Tests.Get_Properties, Factory => Fact); end if; end Set_Up; -- ------------------------------ -- Test a GET request and the lifecycles that this implies. -- ------------------------------ procedure Test_Get_Lifecycle (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased ASF.Applications.Tests.Form_Bean; Listener : aliased Test_Phase_Listener; Handler : constant Lifecycle_Access := ASF.Tests.Get_Application.Get_Lifecycle_Handler; begin Handler.Add_Phase_Listener (Listener'Unchecked_Access); Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt"); Listener.Check_Get_Counters (T, 1); Listener.Check_Post_Counters (T, 0); Handler.Remove_Phase_Listener (Listener'Unchecked_Access); exception when others => Handler.Remove_Phase_Listener (Listener'Unchecked_Access); raise; end Test_Get_Lifecycle; -- ------------------------------ -- Test a GET+POST request with submitted values and an action method called on the bean. -- ------------------------------ procedure Test_Post_Lifecycle (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Form : aliased ASF.Applications.Tests.Form_Bean; Listener : aliased Test_Phase_Listener; Handler : constant Lifecycle_Access := ASF.Tests.Get_Application.Get_Lifecycle_Handler; begin Handler.Add_Phase_Listener (Listener'Unchecked_Access); Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access, Storage => STATIC)); Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt"); Request.Set_Parameter ("formText", "1"); Request.Set_Parameter ("name", "John"); Request.Set_Parameter ("password", "12345"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("ok", "1"); Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post.txt"); Listener.Check_Post_Counters (T, 1); Listener.Check_Get_Counters (T, 2); Handler.Remove_Phase_Listener (Listener'Unchecked_Access); exception when others => Handler.Remove_Phase_Listener (Listener'Unchecked_Access); raise; end Test_Post_Lifecycle; -- ------------------------------ -- Check that the RESTORE_VIEW and RENDER_RESPONSE counters have the given value. -- ------------------------------ procedure Check_Get_Counters (Listener : in Test_Phase_Listener; T : in out Test'Class; Value : in Natural) is use ASF.Events.Phases; begin Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (RESTORE_VIEW), "Invalid before RESTORE_VIEW count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (RESTORE_VIEW), "Invalid after RESTORE_VIEW count"); Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (RENDER_RESPONSE), "Invalid before RENDER_RESPONSE count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (RENDER_RESPONSE), "Invalid after RENDER_RESPONSE count"); end Check_Get_Counters; -- ------------------------------ -- Check that the APPLY_REQUESTS .. INVOKE_APPLICATION counters have the given value. -- ------------------------------ procedure Check_Post_Counters (Listener : in Test_Phase_Listener; T : in out Test'Class; Value : in Natural) is use ASF.Events.Phases; begin Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (APPLY_REQUEST_VALUES), "Invalid before APPLY_REQUEST_VALUES count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (APPLY_REQUEST_VALUES), "Invalid after APPLY_REQUEST_VALUES count"); Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (PROCESS_VALIDATION), "Invalid before PROCESS_VALIDATION count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (PROCESS_VALIDATION), "Invalid after PROCESS_VALIDATION count"); Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (UPDATE_MODEL_VALUES), "Invalid before UPDATE_MODEL_VALUES count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (UPDATE_MODEL_VALUES), "Invalid after UPDATE_MODEL_VALUES count"); Util.Tests.Assert_Equals (T, Value, Listener.Before_Count (INVOKE_APPLICATION), "Invalid before INVOKE_APPLICATION count"); Util.Tests.Assert_Equals (T, Value, Listener.After_Count (INVOKE_APPLICATION), "Invalid after INVOKE_APPLICATION count"); end Check_Post_Counters; -- ------------------------------ -- Notifies that the lifecycle phase described by the event is about to begin. -- ------------------------------ procedure Before_Phase (Listener : in Test_Phase_Listener; Event : in ASF.Events.Phases.Phase_Event'Class) is begin Listener.Before_Count (Event.Phase) := Listener.Before_Count (Event.Phase) + 1; end Before_Phase; -- ------------------------------ -- Notifies that the lifecycle phase described by the event has finished. -- ------------------------------ procedure After_Phase (Listener : in Test_Phase_Listener; Event : in ASF.Events.Phases.Phase_Event'Class) is begin Listener.After_Count (Event.Phase) := Listener.After_Count (Event.Phase) + 1; end After_Phase; -- ------------------------------ -- Return the phase that this listener is interested in processing the <b>Phase_Event</b> -- events. If the listener is interested by several events, it should return <b>ANY_PHASE</b>. -- ------------------------------ function Get_Phase (Listener : in Test_Phase_Listener) return ASF.Events.Phases.Phase_Type is begin return Listener.Phase; end Get_Phase; overriding procedure Initialize (Listener : in out Test_Phase_Listener) is begin Listener.After_Count := new Phase_Counters '(others => 0); Listener.Before_Count := new Phase_Counters '(others => 0); end Initialize; overriding procedure Finalize (Listener : in out Test_Phase_Listener) is procedure Free is new Ada.Unchecked_Deallocation (Object => Phase_Counters, Name => Phase_Counters_Array); begin Free (Listener.After_Count); Free (Listener.Before_Count); end Finalize; end ASF.Lifecycles.Tests;
Remove unused use clauses
Remove unused use clauses
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
a096c845822ae61bb27adc7f72902f209a65681a
awt/src/wayland/awt-wayland-windows.ads
awt/src/wayland/awt-wayland-windows.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 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. private with Ada.Finalization; private with Ada.Strings.Unbounded; private with Wayland.Cursor; private with Wayland.EGL; private with Wayland.Protocols.Xdg_Shell; private with Wayland.Protocols.Presentation_Time; private with Wayland.Protocols.Idle_Inhibit_Unstable_V1; private with Wayland.Protocols.Xdg_Decoration_Unstable_V1; private with Wayland.Protocols.Pointer_Constraints_Unstable_V1; private with EGL.Objects.Displays; private with EGL.Objects.Surfaces; with Wayland.Protocols.Client; with EGL.Objects.Configs; with EGL.Objects.Contexts; with AWT.Inputs; with AWT.Monitors; with AWT.Windows; package AWT.Wayland.Windows is pragma Preelaborate; type Wayland_Window is abstract limited new AWT.Windows.Window with private; procedure Sleep_Until_Swap (Object : in out Wayland_Window; Time_To_Swap : Duration) is abstract; ---------------------------------------------------------------------------- -- Internal Subprograms -- ---------------------------------------------------------------------------- procedure Set_State (Object : in out Wayland_Window; State : AWT.Inputs.Pointer_State); procedure Set_State (Object : in out Wayland_Window; State : AWT.Inputs.Keyboard_State); procedure Update_Cursor (Object : in out Wayland_Window) is null; procedure Restore_Cursor (Object : in out Wayland_Window); type Surface_With_Window (Window : not null access Wayland_Window) is new WP.Client.Surface with null record; procedure Update_Animated_Cursor (Window : not null access Wayland_Window); procedure Set_EGL_Data (Object : in out Wayland_Window; Context : EGL.Objects.Contexts.Context; Config : EGL.Objects.Configs.Config; sRGB : Boolean); procedure Make_Current (Object : in out Wayland_Window; Context : Standard.EGL.Objects.Contexts.Context); private package SU renames Ada.Strings.Unbounded; package II renames WP.Idle_Inhibit_Unstable_V1; package XD renames WP.Xdg_Decoration_Unstable_V1; package PC renames WP.Pointer_Constraints_Unstable_V1; package WC renames Standard.Wayland.Cursor; subtype Unsigned_32 is Standard.Wayland.Unsigned_32; type Xdg_Surface_With_Window (Window : not null access Wayland_Window) is new WP.Xdg_Shell.Xdg_Surface with null record; type Xdg_Toplevel_With_Window (Window : not null access Wayland_Window) is new WP.Xdg_Shell.Xdg_Toplevel with null record; type Toplevel_Decoration_With_Window (Window : not null access Wayland_Window) is new XD.Toplevel_Decoration_V1 with null record; type Locked_Pointer_With_Window (Window : not null access Wayland_Window) is new PC.Locked_Pointer_V1 with null record; type Frame; type Feedback_With_Frame (Data : not null access Frame) is new WP.Presentation_Time.Presentation_Feedback with null record; type Frame_Index is mod 16; type Frame is limited record Window : access Wayland_Window; Feedback : Feedback_With_Frame (Frame'Access); Index : Frame_Index; Start, Stop : Duration := 0.0; end record; type Frame_Array is array (Frame_Index) of Frame; function Make_Frames (Window : not null access Wayland_Window) return Frame_Array with Post => (for all FB of Make_Frames'Result => FB.Window /= null); protected type Frame_Handler_With_Window (Window : not null access Wayland_Window) is entry Before_Swap_Buffers (Time_To_Swap : out Duration; Do_Swap : out Boolean); procedure After_Swap_Buffers; procedure On_Frame_Output (Index : Frame_Index; Refresh : Duration); procedure On_Frame_Presented (Index : Frame_Index; Timestamp, Refresh : Duration); procedure On_Frame_Discarded (Index : Frame_Index); procedure Set_Size (Width, Height : Positive; Margin : Natural; Serial : Unsigned_32); entry Set_Has_Buffer (Value : Boolean); procedure Finalize; private Max_In_Flight : Duration := 0.0; Latest_Stop : Duration := 0.0; Default_Refresh : Duration := 0.0; Resize_Width, Resize_Height, Resize_Margin : Natural := 0; Resize_Serial : Unsigned_32; Has_Buffer : Boolean := False; Swapping : Boolean := False; Pending : Natural := 0; Frames : Frame_Array := Make_Frames (Window); end Frame_Handler_With_Window; type Cursor_Hotspot_Coordinate is array (AWT.Inputs.Dimension) of Natural; type Wayland_Window is abstract limited new Ada.Finalization.Limited_Controlled and AWT.Windows.Window with record Pending_State, Current_State : AWT.Windows.Window_State; Pending_Scale, Current_Scale : Positive := 1; Restore_Width : Natural := 0; Restore_Height : Natural := 0; Restore_Margin : Natural := 0; Restore_ID : SU.Unbounded_String; Restore_Title : SU.Unbounded_String; Initial_Configure : Boolean := True; Surface : Surface_With_Window (Wayland_Window'Access); XDG_Surface : Xdg_Surface_With_Window (Wayland_Window'Access); XDG_Toplevel : Xdg_Toplevel_With_Window (Wayland_Window'Access); Decoration : Toplevel_Decoration_With_Window (Wayland_Window'Access); Frame_Handler : Frame_Handler_With_Window (Wayland_Window'Access); -- Wayland.EGL EGL_Window : Standard.Wayland.EGL.Window; -- EGL EGL_Surface : EGL.Objects.Surfaces.Surface (EGL.Objects.Displays.Wayland); EGL_Context : EGL.Objects.Contexts.Context (EGL.Objects.Displays.Wayland); EGL_Config : EGL.Objects.Configs.Config; EGL_sRGB : Boolean; Should_Close : Boolean := False with Atomic; Idle_Inhibitor : II.Idle_Inhibitor_V1; Pointer_State : AWT.Inputs.Pointer_State; Keyboard_State : AWT.Inputs.Keyboard_State; Locked_Pointer : Locked_Pointer_With_Window (Wayland_Window'Access); Locked_Position : AWT.Inputs.Coordinate; Unlocked_Pointer_Mode : AWT.Inputs.Pointer_Mode; Raw_Pointer_Motion : Boolean := False; Cursor_Surface : WP.Client.Surface; Cursor_Hotspot : Cursor_Hotspot_Coordinate := (others => 0); Cursor : AWT.Inputs.Cursors.Pointer_Cursor := AWT.Inputs.Cursors.Default; Cursor_Images : Positive := 1; end record; overriding procedure Create_Window (Object : aliased in out Wayland_Window; ID, Title : String; Width, Height : Positive; Visible, Resizable, Decorated : Boolean := True; Transparent : Boolean := False); overriding procedure Finalize (Object : in out Wayland_Window); overriding procedure Set_Application_ID (Object : in out Wayland_Window; ID : String); overriding procedure Set_Application_Title (Object : in out Wayland_Window; Title : String); overriding procedure Set_Size (Object : in out Wayland_Window; Width, Height : Positive); overriding procedure Set_Size_Limits (Object : in out Wayland_Window; Min_Width, Min_Height, Max_Width, Max_Height : Natural); overriding procedure Set_Size_Mode (Object : in out Wayland_Window; Mode : AWT.Windows.Size_Mode); overriding procedure Set_Size_Mode (Object : in out Wayland_Window; Mode : AWT.Windows.Size_Mode; Monitor : AWT.Monitors.Monitor'Class); overriding procedure Set_Framebuffer_Scale (Object : in out Wayland_Window; Scale : Positive); overriding procedure Set_Raw_Pointer_Motion (Object : in out Wayland_Window; Enable : Boolean); overriding procedure Set_Margin (Object : in out Wayland_Window; Margin : Natural); overriding procedure Set_Visible (Object : in out Wayland_Window; Visible : Boolean); overriding procedure Set_Pointer_Cursor (Object : in out Wayland_Window; Cursor : AWT.Inputs.Cursors.Pointer_Cursor); overriding procedure Set_Pointer_Mode (Object : in out Wayland_Window; Mode : AWT.Inputs.Pointer_Mode); overriding function Raw_Pointer_Motion (Object : Wayland_Window) return Boolean; overriding function State (Object : Wayland_Window) return AWT.Windows.Window_State; overriding function State (Object : Wayland_Window) return AWT.Windows.Framebuffer_State; overriding function State (Object : Wayland_Window) return AWT.Inputs.Pointer_State; overriding function State (Object : Wayland_Window) return AWT.Inputs.Keyboard_State; overriding procedure Close (Object : in out Wayland_Window); overriding function Should_Close (Object : Wayland_Window) return Boolean; overriding procedure Swap_Buffers (Object : in out Wayland_Window); overriding procedure Set_Vertical_Sync (Object : in out Wayland_Window; Enable : Boolean); overriding function On_Close (Object : Wayland_Window) return Boolean; function On_Change_Cursor (Object : in out Wayland_Window; Name : AWT.Inputs.Cursors.Pointer_Cursor; Cursor : WC.Cursor'Class) return WC.Cursor_Image'Class; end AWT.Wayland.Windows;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 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. private with Ada.Finalization; private with Ada.Strings.Unbounded; private with Wayland.Cursor; private with Wayland.EGL; private with Wayland.Protocols.Xdg_Shell; private with Wayland.Protocols.Presentation_Time; private with Wayland.Protocols.Idle_Inhibit_Unstable_V1; private with Wayland.Protocols.Xdg_Decoration_Unstable_V1; private with Wayland.Protocols.Pointer_Constraints_Unstable_V1; private with EGL.Objects.Displays; private with EGL.Objects.Surfaces; with Wayland.Protocols.Client; with EGL.Objects.Configs; with EGL.Objects.Contexts; with AWT.Inputs; with AWT.Monitors; with AWT.Windows; -- To display a window on the screen via Wayland quite a few objects -- are needed: -- -- - Objects wl_compositor and xdg_wm_base are globals that are binded -- in package AWT.Registry. -- -- - Objects xdg_surface and xdg_toplevel are objects from the xdg-shell -- protocol that will cause the compositor to eventually display a window -- (the wl_surface object) on the screen. -- -- - Object wl_egl_window is created via the libwayland-egl library and -- is used to get an EGLSurface, which is attached to an EGLContext for -- use by eglSwapBuffers(). When this function is called, it attaches a -- buffer (the default framebuffer) to the wl_surface and then commits -- this surface. -- -- wl_display -- | -- v -- wl_registry -- | \ -- | -> wl_compositor -- | | -- v v -- xdg_wm_base + wl_surface -- | \ -- v -> wl_egl_window -- xdg_surface | -- | v -- v EGLSurface (via eglCreatePlatformWindowSurfaceEXT()) -- xdg_toplevel | -- v -- attach EGLSurface to EGLContext -- with eglMakeCurrent() package AWT.Wayland.Windows is pragma Preelaborate; type Wayland_Window is abstract limited new AWT.Windows.Window with private; procedure Sleep_Until_Swap (Object : in out Wayland_Window; Time_To_Swap : Duration) is abstract; ---------------------------------------------------------------------------- -- Internal Subprograms -- ---------------------------------------------------------------------------- procedure Set_State (Object : in out Wayland_Window; State : AWT.Inputs.Pointer_State); procedure Set_State (Object : in out Wayland_Window; State : AWT.Inputs.Keyboard_State); procedure Update_Cursor (Object : in out Wayland_Window) is null; procedure Restore_Cursor (Object : in out Wayland_Window); type Surface_With_Window (Window : not null access Wayland_Window) is new WP.Client.Surface with null record; procedure Update_Animated_Cursor (Window : not null access Wayland_Window); procedure Set_EGL_Data (Object : in out Wayland_Window; Context : EGL.Objects.Contexts.Context; Config : EGL.Objects.Configs.Config; sRGB : Boolean); procedure Make_Current (Object : in out Wayland_Window; Context : Standard.EGL.Objects.Contexts.Context); private package SU renames Ada.Strings.Unbounded; package II renames WP.Idle_Inhibit_Unstable_V1; package XD renames WP.Xdg_Decoration_Unstable_V1; package PC renames WP.Pointer_Constraints_Unstable_V1; package WC renames Standard.Wayland.Cursor; subtype Unsigned_32 is Standard.Wayland.Unsigned_32; type Xdg_Surface_With_Window (Window : not null access Wayland_Window) is new WP.Xdg_Shell.Xdg_Surface with null record; type Xdg_Toplevel_With_Window (Window : not null access Wayland_Window) is new WP.Xdg_Shell.Xdg_Toplevel with null record; type Toplevel_Decoration_With_Window (Window : not null access Wayland_Window) is new XD.Toplevel_Decoration_V1 with null record; type Locked_Pointer_With_Window (Window : not null access Wayland_Window) is new PC.Locked_Pointer_V1 with null record; type Frame; type Feedback_With_Frame (Data : not null access Frame) is new WP.Presentation_Time.Presentation_Feedback with null record; type Frame_Index is mod 16; type Frame is limited record Window : access Wayland_Window; Feedback : Feedback_With_Frame (Frame'Access); Index : Frame_Index; Start, Stop : Duration := 0.0; end record; type Frame_Array is array (Frame_Index) of Frame; function Make_Frames (Window : not null access Wayland_Window) return Frame_Array with Post => (for all FB of Make_Frames'Result => FB.Window /= null); protected type Frame_Handler_With_Window (Window : not null access Wayland_Window) is entry Before_Swap_Buffers (Time_To_Swap : out Duration; Do_Swap : out Boolean); procedure After_Swap_Buffers; procedure On_Frame_Output (Index : Frame_Index; Refresh : Duration); procedure On_Frame_Presented (Index : Frame_Index; Timestamp, Refresh : Duration); procedure On_Frame_Discarded (Index : Frame_Index); procedure Set_Size (Width, Height : Positive; Margin : Natural; Serial : Unsigned_32); entry Set_Has_Buffer (Value : Boolean); procedure Finalize; private Max_In_Flight : Duration := 0.0; Latest_Stop : Duration := 0.0; Default_Refresh : Duration := 0.0; Resize_Width, Resize_Height, Resize_Margin : Natural := 0; Resize_Serial : Unsigned_32; Has_Buffer : Boolean := False; Swapping : Boolean := False; Pending : Natural := 0; Frames : Frame_Array := Make_Frames (Window); end Frame_Handler_With_Window; type Cursor_Hotspot_Coordinate is array (AWT.Inputs.Dimension) of Natural; type Wayland_Window is abstract limited new Ada.Finalization.Limited_Controlled and AWT.Windows.Window with record Pending_State, Current_State : AWT.Windows.Window_State; Pending_Scale, Current_Scale : Positive := 1; Restore_Width : Natural := 0; Restore_Height : Natural := 0; Restore_Margin : Natural := 0; Restore_ID : SU.Unbounded_String; Restore_Title : SU.Unbounded_String; Initial_Configure : Boolean := True; Surface : Surface_With_Window (Wayland_Window'Access); XDG_Surface : Xdg_Surface_With_Window (Wayland_Window'Access); XDG_Toplevel : Xdg_Toplevel_With_Window (Wayland_Window'Access); Decoration : Toplevel_Decoration_With_Window (Wayland_Window'Access); Frame_Handler : Frame_Handler_With_Window (Wayland_Window'Access); -- Wayland.EGL EGL_Window : Standard.Wayland.EGL.Window; -- EGL EGL_Surface : EGL.Objects.Surfaces.Surface (EGL.Objects.Displays.Wayland); EGL_Context : EGL.Objects.Contexts.Context (EGL.Objects.Displays.Wayland); EGL_Config : EGL.Objects.Configs.Config; EGL_sRGB : Boolean; Should_Close : Boolean := False with Atomic; Idle_Inhibitor : II.Idle_Inhibitor_V1; Pointer_State : AWT.Inputs.Pointer_State; Keyboard_State : AWT.Inputs.Keyboard_State; Locked_Pointer : Locked_Pointer_With_Window (Wayland_Window'Access); Locked_Position : AWT.Inputs.Coordinate; Unlocked_Pointer_Mode : AWT.Inputs.Pointer_Mode; Raw_Pointer_Motion : Boolean := False; Cursor_Surface : WP.Client.Surface; Cursor_Hotspot : Cursor_Hotspot_Coordinate := (others => 0); Cursor : AWT.Inputs.Cursors.Pointer_Cursor := AWT.Inputs.Cursors.Default; Cursor_Images : Positive := 1; end record; overriding procedure Create_Window (Object : aliased in out Wayland_Window; ID, Title : String; Width, Height : Positive; Visible, Resizable, Decorated : Boolean := True; Transparent : Boolean := False); overriding procedure Finalize (Object : in out Wayland_Window); overriding procedure Set_Application_ID (Object : in out Wayland_Window; ID : String); overriding procedure Set_Application_Title (Object : in out Wayland_Window; Title : String); overriding procedure Set_Size (Object : in out Wayland_Window; Width, Height : Positive); overriding procedure Set_Size_Limits (Object : in out Wayland_Window; Min_Width, Min_Height, Max_Width, Max_Height : Natural); overriding procedure Set_Size_Mode (Object : in out Wayland_Window; Mode : AWT.Windows.Size_Mode); overriding procedure Set_Size_Mode (Object : in out Wayland_Window; Mode : AWT.Windows.Size_Mode; Monitor : AWT.Monitors.Monitor'Class); overriding procedure Set_Framebuffer_Scale (Object : in out Wayland_Window; Scale : Positive); overriding procedure Set_Raw_Pointer_Motion (Object : in out Wayland_Window; Enable : Boolean); overriding procedure Set_Margin (Object : in out Wayland_Window; Margin : Natural); overriding procedure Set_Visible (Object : in out Wayland_Window; Visible : Boolean); overriding procedure Set_Pointer_Cursor (Object : in out Wayland_Window; Cursor : AWT.Inputs.Cursors.Pointer_Cursor); overriding procedure Set_Pointer_Mode (Object : in out Wayland_Window; Mode : AWT.Inputs.Pointer_Mode); overriding function Raw_Pointer_Motion (Object : Wayland_Window) return Boolean; overriding function State (Object : Wayland_Window) return AWT.Windows.Window_State; overriding function State (Object : Wayland_Window) return AWT.Windows.Framebuffer_State; overriding function State (Object : Wayland_Window) return AWT.Inputs.Pointer_State; overriding function State (Object : Wayland_Window) return AWT.Inputs.Keyboard_State; overriding procedure Close (Object : in out Wayland_Window); overriding function Should_Close (Object : Wayland_Window) return Boolean; overriding procedure Swap_Buffers (Object : in out Wayland_Window); overriding procedure Set_Vertical_Sync (Object : in out Wayland_Window; Enable : Boolean); overriding function On_Close (Object : Wayland_Window) return Boolean; function On_Change_Cursor (Object : in out Wayland_Window; Name : AWT.Inputs.Cursors.Pointer_Cursor; Cursor : WC.Cursor'Class) return WC.Cursor_Image'Class; end AWT.Wayland.Windows;
Add a comment to AWT.Wayland.Windows showing a graph of objects
wayland: Add a comment to AWT.Wayland.Windows showing a graph of objects Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
0ec1301f8b9ed09c51e80a8ab7a0f6ceb2d493b4
regtests/ado-drivers-tests.ads
regtests/ado-drivers-tests.ads
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); -- Test the Set_Server operation. procedure Test_Set_Connection_Server (T : in out Test); -- Test the Set_Port operation. procedure Test_Set_Connection_Port (T : in out Test); -- Test the connection operations on an empty connection. procedure Test_Empty_Connection (T : in out Test); end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); -- Test the Set_Server operation. procedure Test_Set_Connection_Server (T : in out Test); -- Test the Set_Port operation. procedure Test_Set_Connection_Port (T : in out Test); -- Test the Set_Database operation. procedure Test_Set_Connection_Database (T : in out Test); -- Test the connection operations on an empty connection. procedure Test_Empty_Connection (T : in out Test); end ADO.Drivers.Tests;
Declare Test_Set_Connection_Database procedure
Declare Test_Set_Connection_Database procedure
Ada
apache-2.0
stcarrez/ada-ado
2f506db8c4727c98ee9200915d682286c46cb2fc
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- 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 AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Servlets.Faces; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : AWA.Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Services.Tests; with AWA.Wikis.Parsers.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Services.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with ASF.Server.Web; with ASF.Servlets.Faces; with ASF.Server.Tests; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Wikis.Parsers.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Blogs.Services.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Services.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : AWA.Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Add the images plugin unit tests
Add the images plugin unit tests
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5c5457c9da423bf16a62c5259e852f453f83e452
src/sys/lzma/util-streams-buffered-lzma.adb
src/sys/lzma/util-streams-buffered-lzma.adb
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 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 Lzma.Check; with Lzma.Container; with Interfaces.C; with Ada.IO_Exceptions; package body Util.Streams.Buffered.Lzma is use type Interfaces.C.size_t; use type Base.lzma_ret; subtype size_t is Interfaces.C.size_t; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Compress_Stream; Output : access Output_Stream'Class; Size : in Positive) is Result : Base.lzma_ret; begin Output_Buffer_Stream (Stream).Initialize (Output, Size); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; Result := Container.lzma_easy_encoder (Stream.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Device_Error with "Cannot initialize compressor"; end if; end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Compress_Stream) is begin Stream.Flush; Output_Buffer_Stream (Stream).Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Last_Pos : Ada.Streams.Stream_Element_Offset; Encoded : Boolean := False; Result : Base.lzma_ret; begin loop if Stream.Stream.avail_in = 0 then Stream.Stream.next_in := Buffer (Buffer'First)'Unrestricted_Access; Stream.Stream.avail_in := size_t (Buffer'Length); Encoded := True; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK or (Stream.Stream.avail_in = 0 and Encoded); end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Compress_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset; Result : Base.lzma_ret; begin Stream.Stream.next_in := null; Stream.Stream.avail_in := 0; loop Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_FINISH); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK; end loop; end Flush; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Compress_Stream) is begin Object.Flush; Output_Buffer_Stream (Object).Finalize; Base.lzma_end (Object.Stream'Unchecked_Access); end Finalize; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Decompress_Stream; Input : access Input_Stream'Class; Size : in Positive) is Result : Base.lzma_ret; begin Input_Buffer_Stream (Stream).Initialize (Input, Size); Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_in := 0; Result := Container.lzma_stream_decoder (Stream.Stream'Unchecked_Access, Long_Long_Integer'Last, Container.LZMA_CONCATENATED); if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Device_Error with "Cannot initialize decompressor"; end if; end Initialize; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Read (Stream : in out Decompress_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is use type Base.lzma_action; Result : Base.lzma_ret; begin Stream.Stream.next_out := Into (Into'First)'Unrestricted_Access; Stream.Stream.avail_out := Into'Length; loop if Stream.Stream.avail_in = 0 and not Stream.Is_Eof and Stream.Action = Base.LZMA_RUN then Stream.Fill; if Stream.Write_Pos >= Stream.Read_Pos then Stream.Stream.avail_in := size_t (Stream.Write_Pos - Stream.Read_Pos); Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; else Stream.Stream.avail_in := 0; Stream.Stream.next_in := null; Stream.Action := Base.LZMA_FINISH; end if; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Stream.Action); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (Stream.Stream.avail_out) - 1; return; end if; if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Data_Error with "Decompression error"; end if; end loop; end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Decompress_Stream) is begin Base.lzma_end (Object.Stream'Unchecked_Access); Input_Buffer_Stream (Object).Finalize; end Finalize; end Util.Streams.Buffered.Lzma;
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 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 Lzma.Check; with Lzma.Container; with Interfaces.C; with Ada.IO_Exceptions; package body Util.Streams.Buffered.Lzma is use type Interfaces.C.size_t; use type Base.lzma_ret; subtype size_t is Interfaces.C.size_t; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Compress_Stream; Output : access Output_Stream'Class; Size : in Positive) is Result : Base.lzma_ret; begin Output_Buffer_Stream (Stream).Initialize (Output, Size); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; Result := Container.lzma_easy_encoder (Stream.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Device_Error with "Cannot initialize compressor"; end if; end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Compress_Stream) is begin Stream.Flush; Output_Buffer_Stream (Stream).Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Last_Pos : Ada.Streams.Stream_Element_Offset; Encoded : Boolean := False; Result : Base.lzma_ret; begin loop if Stream.Stream.avail_in = 0 then Stream.Stream.next_in := Buffer (Buffer'First)'Unrestricted_Access; Stream.Stream.avail_in := size_t (Buffer'Length); Encoded := True; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK or (Stream.Stream.avail_in = 0 and Encoded); end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Compress_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset; Result : Base.lzma_ret; begin -- Stream is closed, ignore the flush. if Stream.Buffer = null then return; end if; Stream.Stream.next_in := null; Stream.Stream.avail_in := 0; loop Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_FINISH); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; if Last_Pos >= Stream.Buffer'First then Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); end if; Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK; end loop; end Flush; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Compress_Stream) is begin Object.Flush; Output_Buffer_Stream (Object).Finalize; Base.lzma_end (Object.Stream'Unchecked_Access); end Finalize; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Decompress_Stream; Input : access Input_Stream'Class; Size : in Positive) is Result : Base.lzma_ret; begin Input_Buffer_Stream (Stream).Initialize (Input, Size); Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_in := 0; Result := Container.lzma_stream_decoder (Stream.Stream'Unchecked_Access, Long_Long_Integer'Last, Container.LZMA_CONCATENATED); if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Device_Error with "Cannot initialize decompressor"; end if; end Initialize; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Read (Stream : in out Decompress_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is use type Base.lzma_action; Result : Base.lzma_ret; begin Stream.Stream.next_out := Into (Into'First)'Unrestricted_Access; Stream.Stream.avail_out := Into'Length; loop if Stream.Stream.avail_in = 0 and not Stream.Is_Eof and Stream.Action = Base.LZMA_RUN then Stream.Fill; if Stream.Write_Pos >= Stream.Read_Pos then Stream.Stream.avail_in := size_t (Stream.Write_Pos - Stream.Read_Pos); Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; else Stream.Stream.avail_in := 0; Stream.Stream.next_in := null; Stream.Action := Base.LZMA_FINISH; end if; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Stream.Action); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (Stream.Stream.avail_out) - 1; return; end if; if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Data_Error with "Decompression error"; end if; end loop; end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Decompress_Stream) is begin Base.lzma_end (Object.Stream'Unchecked_Access); Input_Buffer_Stream (Object).Finalize; end Finalize; end Util.Streams.Buffered.Lzma;
Fix Flush to avoid trying to flush if the stream was closed
Fix Flush to avoid trying to flush if the stream was closed
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d94d09cf96898a80fa4f0702c6ad95f383de9d3d
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. -- -- === 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); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- 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); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; 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. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === 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); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- 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); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; 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
cb3cc196e290521c762d348cc6327ae94dc43960
src/util-properties-bundles.adb
src/util-properties-bundles.adb
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; with Util.Strings.Maps; package body Util.Properties.Bundles is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; type Manager_Object_Access is access all Manager; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager; Name : in Value; Item : in Value); -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access); function Get_Names (Self : in Manager; Prefix : in String) return Name_Array; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private use type Util.Properties.Manager_Access; package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; procedure Free is new Ada.Unchecked_Deallocation (Manager, Manager_Object_Access); end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is use type Util.Properties.Interface_P.Manager_Access; begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count + 1; else Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end if; end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; use type Util.Properties.Manager_Access; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Info ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Bundle.Impl.Count := Bundle.Impl.Count + 1; Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Debug ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in Value) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; -- ------------------------------ -- Returns the property value. Raises an exception if not found. -- ------------------------------ function Get (Self : in Manager; Name : in Value) return Value is begin return Self.Props.Get (Name); exception when NO_PROPERTY => declare Iter : Cursor := Self.List.First; begin while Has_Element (Iter) loop begin return Element (Iter).all.Get (Name); exception when NO_PROPERTY => Iter := Next (Iter); end; end loop; end; raise; end Get; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is pragma Unreferenced (Self); pragma Unreferenced (Name); pragma Unreferenced (Item); begin raise NOT_WRITEABLE with "Bundle is readonly"; end Insert; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager; Name : in Value; Item : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access) is pragma Unreferenced (Self); Item : Manager_Object_Access := Manager (Obj.all)'Access; begin Free (Item); end Delete; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is Result : Name_Array (1 .. 2); Iter : constant Cursor := Self.List.First; begin while Has_Element (Iter) loop declare M : constant Util.Properties.Manager_Access := Element (Iter); N : constant Name_Array := M.Get_Names (Prefix); begin return N; end; end loop; return Result; end Get_Names; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 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 Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Strings.Fixed; with Util.Log.Loggers; with Util.Files; package body Util.Properties.Bundles is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles"); procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Bundle_Manager_Access); -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is new Util.Properties.Interface_P.Manager with private; type Manager_Object_Access is access all Manager; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager; Name : in Value; Item : in Value); -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)); procedure Load_Properties (Self : in out Manager; File : in String); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access); function Get_Names (Self : in Manager; Prefix : in String) return Name_Array; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access); private use type Util.Properties.Manager_Access; package PropertyList is new Ada.Containers.Vectors (Element_Type => Util.Properties.Manager_Access, Index_Type => Natural, "=" => "="); type Manager is new Util.Properties.Interface_P.Manager with record List : PropertyList.Vector; Props : aliased Util.Properties.Manager; end record; procedure Free is new Ada.Unchecked_Deallocation (Manager, Manager_Object_Access); end Interface_P; procedure Add_Bundle (Self : in out Manager; Props : in Manager_Access) is use type Util.Properties.Interface_P.Manager_Access; begin Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props); end Add_Bundle; procedure Initialize (Object : in out Manager) is use Util.Properties.Interface_P; begin Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end Initialize; procedure Adjust (Object : in out Manager) is use Util.Properties.Interface_P; begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count + 1; else Object.Impl := new Util.Properties.Bundles.Interface_P.Manager; Object.Impl.Count := 1; end if; end Adjust; -- ------------------------------ -- Initialize the bundle factory and specify where the property files are stored. -- ------------------------------ procedure Initialize (Factory : in out Loader; Path : in String) is begin Log.Info ("Initialize bundle factory to load from {0}", Path); Factory.Path := To_Unbounded_String (Path); end Initialize; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class) is Found : Boolean := False; begin Log.Info ("Load bundle {0} for language {1}", Name, Locale); Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Load_Bundle (Factory, Name, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; Find_Bundle (Factory, Name, Locale, Bundle, Found); if not Found then Log.Error ("Bundle {0} not found", Name); raise NO_BUNDLE with "No bundle '" & Name & "'"; end if; end if; end Load_Bundle; -- ------------------------------ -- Find the bundle with the given name and for the given locale name. -- ------------------------------ procedure Find_Bundle (Factory : in out Loader; Name : in String; Locale : in String; Bundle : out Manager'Class; Found : out Boolean) is use Ada.Strings; use type Util.Properties.Manager_Access; Loc_Name : constant String := '_' & Locale; Last_Pos : Integer := Loc_Name'Last; begin Log.Info ("Looking for bundle {0} and language {1}", Name, Locale); Found := False; Factory.Lock.Read; declare Pos : Bundle_Map.Cursor; begin while Last_Pos + 1 >= Loc_Name'First loop declare Bundle_Name : aliased constant String := Name & Loc_Name (Loc_Name'First .. Last_Pos); begin Log.Debug ("Searching for {0}", Bundle_Name); Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access); if Bundle_Map.Has_Element (Pos) then Bundle.Finalize; Bundle.Impl := Bundle_Map.Element (Pos).Impl; Bundle.Impl.Count := Bundle.Impl.Count + 1; Found := True; exit; end if; end; if Last_Pos > Loc_Name'First then Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1; else Last_Pos := Last_Pos - 1; end if; end loop; exception when others => Factory.Lock.Release_Read; raise; end; Factory.Lock.Release_Read; end Find_Bundle; -- ------------------------------ -- Load the bundle with the given name and for the given locale name. -- ------------------------------ procedure Load_Bundle (Factory : in out Loader; Name : in String; Found : out Boolean) is use Ada.Directories; use Ada.Strings; use Util.Strings; use Ada.Containers; use Util.Strings.String_Set; use Bundle_Map; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean); Path : constant String := To_String (Factory.Path); Pattern : constant String := Name & "*.properties"; Names : Util.Strings.String_Set.Set; procedure Process_File (Name : in String; File_Path : in String; Done : out Boolean) is subtype Cursor is Bundle_Map.Cursor; Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11); Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access); Bundle_Name : Name_Access; Bundle : Bundle_Manager_Access; begin Log.Debug ("Loading file {0}", File_Path); if Bundle_Map.Has_Element (Pos) then Bundle := Bundle_Map.Element (Pos); else Bundle := new Manager; Bundle_Name := new String '(Base_Name); Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle); Names.Insert (Bundle_Name); end if; Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path); Found := True; Done := False; end Process_File; begin Log.Info ("Reading bundle {1} in directory {0}", Path, Name); Found := False; Factory.Lock.Write; begin Util.Files.Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Process_File'Access, Going => Ada.Strings.Backward); -- Link the property files to implement the localization default rules. while Names.Length > 0 loop declare Name_Pos : String_Set.Cursor := Names.First; Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos); Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward); Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name); Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos); begin Names.Delete (Name_Pos); -- Associate the property bundle to the first existing parent -- Ex: message_fr_CA -> message_fr -- message_fr_CA -> message while Idx > 0 loop declare Name : aliased constant String := Bundle_Name (Bundle_Name'First .. Idx - 1); Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Name'Unchecked_Access); begin if Bundle_Map.Has_Element (Pos) then Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access); Idx := 0; else Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward); end if; end; end loop; end; end loop; exception when others => Factory.Lock.Release_Write; raise; end; Factory.Lock.Release_Write; exception when Name_Error => Log.Error ("Cannot read directory: {0}", Path); end Load_Bundle; -- Implementation of the Bundle -- (this allows to decouples the implementation from the API) package body Interface_P is use PropertyList; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Manager; Name : in Value) return Boolean is Iter : Cursor := Self.List.First; begin if Self.Props.Exists (Name) then return True; end if; while Has_Element (Iter) loop if Element (Iter).Exists (Name) then return True; end if; Iter := Next (Iter); end loop; return False; end Exists; -- ------------------------------ -- Returns the property value. Raises an exception if not found. -- ------------------------------ function Get (Self : in Manager; Name : in Value) return Value is begin return Self.Props.Get (Name); exception when NO_PROPERTY => declare Iter : Cursor := Self.List.First; begin while Has_Element (Iter) loop begin return Element (Iter).all.Get (Name); exception when NO_PROPERTY => Iter := Next (Iter); end; end loop; end; raise; end Get; procedure Load_Properties (Self : in out Manager; File : in String) is begin Self.Props.Load_Properties (File); end Load_Properties; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is pragma Unreferenced (Self); pragma Unreferenced (Name); pragma Unreferenced (Item); begin raise NOT_WRITEABLE with "Bundle is readonly"; end Insert; -- ------------------------------ -- Set the value of the property. The property is created if it -- does not exists. -- ------------------------------ procedure Set (Self : in out Manager; Name : in Value; Item : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager; Name : in Value) is begin raise NOT_WRITEABLE with "Bundle is readonly"; end Remove; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name, Item : Value)) is begin raise Program_Error with "Iterate is not implemented on Bundle"; end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Manager) return Util.Properties.Interface_P.Manager_Access is pragma Unreferenced (Self); begin return null; end Create_Copy; procedure Delete (Self : in Manager; Obj : in out Util.Properties.Interface_P.Manager_Access) is pragma Unreferenced (Self); Item : Manager_Object_Access := Manager (Obj.all)'Access; begin Free (Item); end Delete; function Get_Names (Self : in Manager; Prefix : in String) return Name_Array is Result : Name_Array (1 .. 2); Iter : constant Cursor := Self.List.First; begin while Has_Element (Iter) loop declare M : constant Util.Properties.Manager_Access := Element (Iter); N : constant Name_Array := M.Get_Names (Prefix); begin return N; end; end loop; return Result; end Get_Names; procedure Add_Bundle (Self : in out Manager; Props : in Util.Properties.Manager_Access) is begin Self.List.Append (Props); end Add_Bundle; end Interface_P; -- ------------------------------ -- Clear the bundle cache -- ------------------------------ procedure Clear_Cache (Factory : in out Loader) is use Util.Strings; use Bundle_Map; function To_String_Access is new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access, Target => Ada.Strings.Unbounded.String_Access); begin Log.Info ("Clearing bundle cache"); Factory.Lock.Write; loop declare Pos : Bundle_Map.Cursor := Factory.Bundles.First; Name : Ada.Strings.Unbounded.String_Access; Node : Bundle_Manager_Access; begin exit when not Has_Element (Pos); Node := Element (Pos); Name := To_String_Access (Key (Pos)); Factory.Bundles.Delete (Pos); Free (Node); Free (Name); end; end loop; Factory.Lock.Release_Write; end Clear_Cache; -- ------------------------------ -- Finalize the bundle loader and clear the cache -- ------------------------------ procedure Finalize (Factory : in out Loader) is begin Clear_Cache (Factory); end Finalize; end Util.Properties.Bundles;
Remove unused with package
Remove unused with package
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
33619cd576c01fd3b000a6c998cd0f98e388c530
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is use type Permissions.Permission_Index; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; -- If the permission has a controller, release it. if Manager.Permissions (Index) /= null then Log.Warn ("Permission {0} is redefined", Name); -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access; begin Free (P); end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Returns True if the security controller is defined for the given permission index. -- ------------------------------ function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean is begin return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null; end Has_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- ------------------------------ -- Prepare the XML parser to read the policy configuration. -- ------------------------------ procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Finish_Config; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); Manager.Prepare_Config (Reader); -- Read the configuration file. Reader.Parse (File); Manager.Finish_Config (Reader); end Read_Policy; -- ------------------------------ -- Initialize the policy manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Policy'Class, Policy_Access); begin -- Release the security controllers. if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop if Manager.Permissions (I) /= null then -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end if; end loop; Free (Manager.Permissions); end if; -- Release the policy instances. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Free (Manager.Policies (I)); end loop; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Contexts; package body Security.Policies is use type Permissions.Permission_Index; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); -- ------------------------------ -- Default Security Controllers -- ------------------------------ -- The <b>Auth_Controller</b> grants the permission if there is a principal. type Auth_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- The <b>Pass_Through_Controller</b> grants access to anybody. type Pass_Through_Controller is limited new Security.Controllers.Controller with null record; -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> was -- authentified (ie, it has a principal). -- ------------------------------ overriding function Has_Permission (Handler : in Auth_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Permission); use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then Log.Debug ("Grant permission because a principal exists"); return True; else return False; end if; end Has_Permission; -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access the URL defined in <b>Permission</b>. -- ------------------------------ overriding function Has_Permission (Handler : in Pass_Through_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Handler, Context, Permission); begin Log.Debug ("Pass through controller grants the permission"); return True; end Has_Permission; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; -- If the permission has a controller, release it. if Manager.Permissions (Index) /= null then Log.Warn ("Permission {0} is redefined", Name); -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access; begin Free (P); end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Returns True if the security controller is defined for the given permission index. -- ------------------------------ function Has_Controller (Manager : in Policy_Manager; Index : in Permissions.Permission_Index) return Boolean is begin return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null; end Has_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- ------------------------------ -- Prepare the XML parser to read the policy configuration. -- ------------------------------ procedure Prepare_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; end Prepare_Config; -- ------------------------------ -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. -- ------------------------------ procedure Finish_Config (Manager : in out Policy_Manager; Reader : in out Util.Serialize.IO.XML.Parser) is begin -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Finish_Config; type Policy_Fields is (FIELD_ALL_PERMISSION, FIELD_AUTH_PERMISSION); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Set_Member (P : in out Policy_Manager'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is Name : constant String := Util.Beans.Objects.To_String (Value); begin case Field is when FIELD_ALL_PERMISSION => P.Add_Permission (Name, new Pass_Through_Controller); when FIELD_AUTH_PERMISSION => P.Add_Permission (Name, new Auth_Controller); end case; end Set_Member; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Manager'Class, Element_Type_Access => Policy_Manager_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Manager'Unchecked_Access); Manager.Prepare_Config (Reader); -- Read the configuration file. Reader.Parse (File); Manager.Finish_Config (Reader); end Read_Policy; -- ------------------------------ -- Initialize the policy manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Policy'Class, Policy_Access); begin -- Release the security controllers. if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop if Manager.Permissions (I) /= null then -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" -- clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler -- bug but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end if; end loop; Free (Manager.Permissions); end if; -- Release the policy instances. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Free (Manager.Policies (I)); end loop; end Finalize; begin Policy_Mapping.Add_Mapping ("all-permission/name", FIELD_ALL_PERMISSION); Policy_Mapping.Add_Mapping ("auth-permission/name", FIELD_AUTH_PERMISSION); end Security.Policies;
Add two default security controllers that can be installed to - grant the permission if the security context has a user principal - always grant the permission
Add two default security controllers that can be installed to - grant the permission if the security context has a user principal - always grant the permission
Ada
apache-2.0
Letractively/ada-security
141bf9f2da6bf731fbc049a930e565b36fe99817
src/wiki-buffers.ads
src/wiki-buffers.ads
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Ada.Finalization; -- == Text Builders == -- The `Util.Texts.Builders` generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The `Builder` type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an `Append` procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the `Iterate` operation that allows to get the content -- collected by the builder. When using the `Iterate` operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that receives -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the `Iterate` operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- private package Wiki.Buffers is pragma Preelaborate; Chunk_Size : constant := 256; type Buffer; type Buffer_Access is access all Buffer; type Buffer (Len : Positive) is limited record Next_Block : Buffer_Access; Last : Natural := 0; Content : Wiki.Strings.WString (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Buffer_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Buffer (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); procedure Next (Content : in out Buffer_Access; Pos : in out Positive) with Inline_Always; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Wiki.Strings.WString); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Wiki.Strings.WChar); -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive); procedure Append (Into : in out Builder; Buffer : in Buffer_Access; From : in Positive); generic with procedure Process (Content : in out Wiki.Strings.WString; Last : out Natural); procedure Inline_Append (Source : in out Builder); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Wiki.Strings.WString)); generic with procedure Process (Content : in Wiki.Strings.WString); procedure Inline_Iterate (Source : in Builder); generic with procedure Process (Content : in out Wiki.Strings.WString); procedure Inline_Update (Source : in out Builder); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Wiki.Strings.WString; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Wiki.Strings.WString; -- Get the element at the given position. function Element (Source : in Builder; Position : in Positive) return Wiki.Strings.WChar; -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. -- generic -- with function Index (Content : in Wiki.Strings.WString) return Natural; -- function Find (Source : in Builder; -- Position : in Positive) return Natural; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Wiki.Strings.WString); procedure Get (Source : in Builder); function Count_Occurence (Buffer : in Buffer_Access; From : in Positive; Item : in Wiki.Strings.WChar) return Natural; procedure Count_Occurence (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar; Count : out Natural); procedure Find (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar); pragma Inline (Length); pragma Inline (Iterate); end Wiki.Buffers;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; with Ada.Finalization; -- == Text Builders == -- The `Util.Texts.Builders` generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The `Builder` type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an `Append` procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the `Iterate` operation that allows to get the content -- collected by the builder. When using the `Iterate` operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that receives -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the `Iterate` operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- private package Wiki.Buffers is pragma Preelaborate; Chunk_Size : constant := 256; type Buffer; type Buffer_Access is access all Buffer; type Buffer (Len : Positive) is limited record Next_Block : Buffer_Access; Last : Natural := 0; Offset : Natural := 0; Content : Wiki.Strings.WString (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Buffer_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Buffer (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); -- Move forward to skip a number of items. procedure Next (Content : in out Buffer_Access; Pos : in out Positive) with Inline_Always; procedure Next (Content : in out Buffer_Access; Pos : in out Positive; Count : in Natural); -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Wiki.Strings.WString); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Wiki.Strings.WChar); -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive); procedure Append (Into : in out Builder; Buffer : in Buffer_Access; From : in Positive); generic with procedure Process (Content : in out Wiki.Strings.WString; Last : out Natural); procedure Inline_Append (Source : in out Builder); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Wiki.Strings.WString)); generic with procedure Process (Content : in Wiki.Strings.WString); procedure Inline_Iterate (Source : in Builder); generic with procedure Process (Content : in out Wiki.Strings.WString); procedure Inline_Update (Source : in out Builder); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Wiki.Strings.WString; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Wiki.Strings.WString; -- Get the element at the given position. function Element (Source : in Builder; Position : in Positive) return Wiki.Strings.WChar; -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. -- generic -- with function Index (Content : in Wiki.Strings.WString) return Natural; -- function Find (Source : in Builder; -- Position : in Positive) return Natural; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Wiki.Strings.WString); procedure Get (Source : in Builder); function Count_Occurence (Buffer : in Buffer_Access; From : in Positive; Item : in Wiki.Strings.WChar) return Natural; procedure Count_Occurence (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar; Count : out Natural); procedure Find (Buffer : in out Buffer_Access; From : in out Positive; Item : in Wiki.Strings.WChar); pragma Inline (Length); pragma Inline (Iterate); end Wiki.Buffers;
Add Next procedure to move forward by several characters
Add Next procedure to move forward by several characters
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
794f7166d89b838ffee9ac7d4ef0957dcaa43004
src/natools-smaz_implementations-base_4096.adb
src/natools-smaz_implementations-base_4096.adb
------------------------------------------------------------------------------ -- Copyright (c) 2016-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.Smaz_Implementations.Base_64_Tools; package body Natools.Smaz_Implementations.Base_4096 is package Tools renames Natools.Smaz_Implementations.Base_64_Tools; use type Ada.Streams.Stream_Element_Offset; procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Base_4096_Digit); -- Read two base-64 symbols and assemble them into a base-4096 number ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Base_4096_Digit) is Low, High : Tools.Base_64_Digit; begin Tools.Next_Digit (Input, Offset, Low); Tools.Next_Digit (Input, Offset, High); Code := Base_4096_Digit (Low) + Base_4096_Digit (High) * 64; end Read_Code; ---------------------- -- Public Interface -- ---------------------- procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Base_4096_Digit; Verbatim_Length : out Natural; Last_Code : in Base_4096_Digit; Variable_Length_Verbatim : in Boolean) is begin Read_Code (Input, Offset, Code); if Code <= Last_Code then Verbatim_Length := 0; elsif not Variable_Length_Verbatim then Verbatim_Length := Positive (Base_4096_Digit'Last - Code + 1); Code := 0; elsif Code < Base_4096_Digit'Last then Verbatim_Length := Positive (Base_4096_Digit'Last - Code); Code := 0; else Read_Code (Input, Offset, Code); Verbatim_Length := Natural (Code) + Natural (Base_4096_Digit'Last - Last_Code); Code := 0; end if; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is begin Tools.Decode (Input, Offset, Output); end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is Code : Tools.Base_64_Digit; begin for I in 1 .. Tools.Image_Length (Verbatim_Length) loop Tools.Next_Digit (Input, Offset, Code); end loop; end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Base_4096_Digit; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Natural := Natural (Base_4096_Digit'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Base_4096_Digit'Last) + Verbatim1_Max_Size + 1; Input_Index : Natural := 0; Remaining_Length, Block_Length : Positive; Result : Ada.Streams.Stream_Element_Count := 0; begin while Input_Index < Input_Length loop Remaining_Length := Input_Length - Input_Index; if Variable_Length_Verbatim and then Remaining_Length > Verbatim1_Max_Size then Block_Length := Positive'Min (Remaining_Length, Verbatim2_Max_Size); Result := Result + 4; else Block_Length := Positive'Min (Remaining_Length, Verbatim1_Max_Size); Result := Result + 2; end if; Result := Result + Tools.Image_Length (Block_Length); Input_Index := Input_Index + Block_Length; end loop; return Result; end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Base_4096_Digit) is Low : constant Tools.Base_64_Digit := Tools.Base_64_Digit (Code mod 64); High : constant Tools.Base_64_Digit := Tools.Base_64_Digit (Code / 64); begin Output (Offset + 0) := Tools.Image (Low); Output (Offset + 1) := Tools.Image (High); Offset := Offset + 2; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Base_4096_Digit; Variable_Length_Verbatim : in Boolean) is Verbatim1_Max_Size : constant Natural := Natural (Base_4096_Digit'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Base_4096_Digit'Last) + Verbatim1_Max_Size + 1; Input_Index : Positive := Input'First; Remaining_Length, Block_Length : Positive; begin while Input_Index in Input'Range loop Remaining_Length := Input'Last - Input_Index + 1; if Variable_Length_Verbatim and then Remaining_Length > Verbatim1_Max_Size then Block_Length := Positive'Min (Remaining_Length, Verbatim2_Max_Size); Write_Code (Output, Offset, Base_4096_Digit'Last); Write_Code (Output, Offset, Base_4096_Digit (Block_Length - Verbatim1_Max_Size - 1)); else Block_Length := Positive'Min (Remaining_Length, Verbatim1_Max_Size); Write_Code (Output, Offset, Base_4096_Digit (Base_4096_Digit'Last - Base_4096_Digit (Block_Length) + 1 - Boolean'Pos (Variable_Length_Verbatim))); end if; Tools.Encode (Input (Input_Index .. Input_Index + Block_Length - 1), Output, Offset); Input_Index := Input_Index + Block_Length; end loop; end Write_Verbatim; end Natools.Smaz_Implementations.Base_4096;
------------------------------------------------------------------------------ -- Copyright (c) 2016-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.Smaz_Implementations.Base_64_Tools; package body Natools.Smaz_Implementations.Base_4096 is package Tools renames Natools.Smaz_Implementations.Base_64_Tools; use type Ada.Streams.Stream_Element_Offset; procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Base_4096_Digit); procedure Read_Code_Or_End (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Base_4096_Digit; Finished : out Boolean); -- Read two base-64 symbols and assemble them into a base-4096 number ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Base_4096_Digit) is Low, High : Tools.Base_64_Digit; begin Tools.Next_Digit (Input, Offset, Low); Tools.Next_Digit (Input, Offset, High); Code := Base_4096_Digit (Low) + Base_4096_Digit (High) * 64; end Read_Code; procedure Read_Code_Or_End (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Base_4096_Digit; Finished : out Boolean) is Low, High : Tools.Base_64_Digit; begin Tools.Next_Digit_Or_End (Input, Offset, Low, Finished); if Finished then return; end if; Tools.Next_Digit (Input, Offset, High); Code := Base_4096_Digit (Low) + Base_4096_Digit (High) * 64; end Read_Code_Or_End; ---------------------- -- Public Interface -- ---------------------- procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Base_4096_Digit; Verbatim_Length : out Natural; Last_Code : in Base_4096_Digit; Variable_Length_Verbatim : in Boolean) is Finished : Boolean; begin Read_Code_Or_End (Input, Offset, Code, Finished); if Finished then Code := Base_4096_Digit'Last; Verbatim_Length := 0; return; end if; if Code <= Last_Code then Verbatim_Length := 0; elsif not Variable_Length_Verbatim then Verbatim_Length := Positive (Base_4096_Digit'Last - Code + 1); Code := 0; elsif Code < Base_4096_Digit'Last then Verbatim_Length := Positive (Base_4096_Digit'Last - Code); Code := 0; else Read_Code (Input, Offset, Code); Verbatim_Length := Natural (Code) + Natural (Base_4096_Digit'Last - Last_Code); Code := 0; end if; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is begin Tools.Decode (Input, Offset, Output); end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is Code : Tools.Base_64_Digit; begin for I in 1 .. Tools.Image_Length (Verbatim_Length) loop Tools.Next_Digit (Input, Offset, Code); end loop; end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Base_4096_Digit; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Natural := Natural (Base_4096_Digit'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Base_4096_Digit'Last) + Verbatim1_Max_Size + 1; Input_Index : Natural := 0; Remaining_Length, Block_Length : Positive; Result : Ada.Streams.Stream_Element_Count := 0; begin while Input_Index < Input_Length loop Remaining_Length := Input_Length - Input_Index; if Variable_Length_Verbatim and then Remaining_Length > Verbatim1_Max_Size then Block_Length := Positive'Min (Remaining_Length, Verbatim2_Max_Size); Result := Result + 4; else Block_Length := Positive'Min (Remaining_Length, Verbatim1_Max_Size); Result := Result + 2; end if; Result := Result + Tools.Image_Length (Block_Length); Input_Index := Input_Index + Block_Length; end loop; return Result; end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Base_4096_Digit) is Low : constant Tools.Base_64_Digit := Tools.Base_64_Digit (Code mod 64); High : constant Tools.Base_64_Digit := Tools.Base_64_Digit (Code / 64); begin Output (Offset + 0) := Tools.Image (Low); Output (Offset + 1) := Tools.Image (High); Offset := Offset + 2; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Base_4096_Digit; Variable_Length_Verbatim : in Boolean) is Verbatim1_Max_Size : constant Natural := Natural (Base_4096_Digit'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Base_4096_Digit'Last) + Verbatim1_Max_Size + 1; Input_Index : Positive := Input'First; Remaining_Length, Block_Length : Positive; begin while Input_Index in Input'Range loop Remaining_Length := Input'Last - Input_Index + 1; if Variable_Length_Verbatim and then Remaining_Length > Verbatim1_Max_Size then Block_Length := Positive'Min (Remaining_Length, Verbatim2_Max_Size); Write_Code (Output, Offset, Base_4096_Digit'Last); Write_Code (Output, Offset, Base_4096_Digit (Block_Length - Verbatim1_Max_Size - 1)); else Block_Length := Positive'Min (Remaining_Length, Verbatim1_Max_Size); Write_Code (Output, Offset, Base_4096_Digit (Base_4096_Digit'Last - Base_4096_Digit (Block_Length) + 1 - Boolean'Pos (Variable_Length_Verbatim))); end if; Tools.Encode (Input (Input_Index .. Input_Index + Block_Length - 1), Output, Offset); Input_Index := Input_Index + Block_Length; end loop; end Write_Verbatim; end Natools.Smaz_Implementations.Base_4096;
check end-of-input in Read_Code
smaz_implementations-base_4096: check end-of-input in Read_Code
Ada
isc
faelys/natools
0b95e7b0ab239c34926b3806152a918ce4fb8215
regtests/ado-queries-tests.adb
regtests/ado-queries-tests.adb
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, 0); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 0); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 1); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index'"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), False); T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; end ADO.Queries.Tests;
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties; with ADO.Drivers.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Drivers.Connections; Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; begin -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), Props.Get ("ado.queries.load", "false") = "true"); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, 0); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, 0); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end; if Mysql_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Mysql_Driver.Get_Driver_Index); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Sqlite_Driver.Get_Driver_Index); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is use ADO.Drivers.Connections; Props : constant Util.Properties.Manager := Util.Tests.Get_Properties; Info : Query_Info_Ref.Ref; begin -- Configure and load the XML queries. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (not Simple_Query.Query.Query.Get.Is_Null, "The simple query was not loaded"); T.Assert (not Index_Query.Query.Query.Get.Is_Null, "The index query was not loaded"); Info := Simple_Query.Query.Query.Get; -- Re-configure but do not reload. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), False); T.Assert (Info.Value = Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Configure again and reload. The query info must have changed. ADO.Queries.Loaders.Initialize (Props.Get ("ado.queries.paths", ".;db"), True); T.Assert (Info.Value /= Simple_Query.Query.Query.Get.Value, "The simple query instance was not changed"); -- Due to the reference held by 'Info', it refers to the data loaded first. T.Assert (Length (Info.Value.Main_Query (0).SQL) > 0, "The old query is not valid"); end Test_Initialize; end ADO.Queries.Tests;
Fix the load query unit test
Fix the load query unit test
Ada
apache-2.0
stcarrez/ada-ado
a14714d17461ea9427a4306f140091ac0754b414
awa/src/awa-events-dispatchers-tasks.adb
awa/src/awa-events-dispatchers-tasks.adb
----------------------------------------------------------------------- -- awa-events-dispatchers-tasks -- AWA Event Dispatchers -- Copyright (C) 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with AWA.Services.Contexts; package body AWA.Events.Dispatchers.Tasks is use Util.Log; use Ada.Strings.Unbounded; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Tasks"); -- ------------------------------ -- Start the dispatcher. -- ------------------------------ overriding procedure Start (Manager : in out Task_Dispatcher) is begin if Manager.Queues.Get_Count > 0 then Log.Info ("Starting the tasks"); if Manager.Workers = null then Manager.Workers := new Consumer_Array (1 .. Manager.Task_Count); end if; for I in Manager.Workers'Range loop Manager.Workers (I).Start (Manager'Unchecked_Access); end loop; else Log.Info ("No event dispatcher task started (no event queue to poll)"); end if; end Start; -- ------------------------------ -- Stop the dispatcher. -- ------------------------------ overriding procedure Stop (Manager : in out Task_Dispatcher) is procedure Free is new Ada.Unchecked_Deallocation (Object => Consumer_Array, Name => Consumer_Array_Access); begin if Manager.Workers /= null then Log.Info ("Stopping the event dispatcher tasks"); for I in Manager.Workers'Range loop if Manager.Workers (I)'Callable then Manager.Workers (I).Stop; else Log.Error ("Event consumer task terminated abnormally"); end if; end loop; Free (Manager.Workers); end if; end Stop; procedure Add_Queue (Manager : in out Task_Dispatcher; Queue : in AWA.Events.Queues.Queue_Ref; Added : out Boolean) is begin Log.Info ("Adding queue {0} to the task dispatcher", Queue.Get_Name); Manager.Queues.Enqueue (Queue); Added := True; end Add_Queue; function Create_Dispatcher (Service : in AWA.Events.Services.Event_Manager_Access; Match : in String; Count : in Positive; Priority : in Positive) return Dispatcher_Access is Result : constant Task_Dispatcher_Access := new Task_Dispatcher; begin Result.Task_Count := Count; Result.Priority := Priority; Result.Match := To_Unbounded_String (Match); Result.Manager := Service.all'Access; return Result.all'Access; end Create_Dispatcher; task body Consumer is Dispatcher : Task_Dispatcher_Access; Time : Duration := 0.01; Do_Work : Boolean := True; Context : AWA.Services.Contexts.Service_Context; begin Log.Info ("Event consumer is ready"); select accept Start (D : in Task_Dispatcher_Access) do Dispatcher := D; end Start; Log.Info ("Event consumer is started"); -- Set the service context. Context.Set_Context (Application => Dispatcher.Manager.Get_Application.all'Access, Principal => null); while Do_Work loop declare Nb_Queues : constant Natural := Dispatcher.Queues.Get_Count; Queue : AWA.Events.Queues.Queue_Ref; Nb_Events : Natural := 0; begin -- We can have several tasks that dispatch events from several queues. -- Each queue in the list must be given the same polling quota. -- Pick a queue and dispatch some pending events. -- Put back the queue in the fifo. for I in 1 .. Nb_Queues loop Dispatcher.Queues.Dequeue (Queue); begin Dispatcher.Dispatch (Queue, Nb_Events); exception when E : others => Log.Error ("Exception when dispatching events", E, True); end; Dispatcher.Queues.Enqueue (Queue); end loop; -- If we processed something, reset the timeout delay and continue polling. -- Otherwise, double the sleep time. if Nb_Events /= 0 then Time := 0.01; else Log.Debug ("Sleeping {0} seconds", Duration'Image (Time)); select accept Stop do Do_Work := False; end Stop; or accept Start (D : in Task_Dispatcher_Access) do Dispatcher := D; end Start; or delay Time; end select; if Time < 60.0 then Time := Time * 2.0; end if; end if; end; end loop; or terminate; end select; end Consumer; end AWA.Events.Dispatchers.Tasks;
----------------------------------------------------------------------- -- awa-events-dispatchers-tasks -- AWA Event Dispatchers -- Copyright (C) 2012, 2015, 2017, 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 Util.Log.Loggers; with AWA.Services.Contexts; package body AWA.Events.Dispatchers.Tasks is use Util.Log; use Ada.Strings.Unbounded; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Tasks"); -- ------------------------------ -- Start the dispatcher. -- ------------------------------ overriding procedure Start (Manager : in out Task_Dispatcher) is begin if Manager.Queues.Get_Count > 0 then Log.Info ("Starting the tasks"); if Manager.Workers = null then Manager.Workers := new Consumer_Array (1 .. Manager.Task_Count); end if; for I in Manager.Workers'Range loop Manager.Workers (I).Start (Manager'Unchecked_Access); end loop; else Log.Info ("No event dispatcher task started (no event queue to poll)"); end if; end Start; -- ------------------------------ -- Stop the dispatcher. -- ------------------------------ overriding procedure Stop (Manager : in out Task_Dispatcher) is procedure Free is new Ada.Unchecked_Deallocation (Object => Consumer_Array, Name => Consumer_Array_Access); begin if Manager.Workers /= null then Log.Info ("Stopping the event dispatcher tasks"); for I in Manager.Workers'Range loop if Manager.Workers (I)'Callable then Manager.Workers (I).Stop; else Log.Error ("Event consumer task terminated abnormally"); end if; end loop; Free (Manager.Workers); end if; end Stop; procedure Add_Queue (Manager : in out Task_Dispatcher; Queue : in AWA.Events.Queues.Queue_Ref; Added : out Boolean) is begin Log.Info ("Adding queue {0} to the task dispatcher", Queue.Get_Name); Manager.Queues.Enqueue (Queue); Added := True; end Add_Queue; function Create_Dispatcher (Service : in AWA.Events.Services.Event_Manager_Access; Match : in String; Count : in Positive; Priority : in Positive) return Dispatcher_Access is Result : constant Task_Dispatcher_Access := new Task_Dispatcher; begin Result.Task_Count := Count; Result.Priority := Priority; Result.Match := To_Unbounded_String (Match); Result.Manager := Service.all'Access; return Result.all'Access; end Create_Dispatcher; task body Consumer is Dispatcher : Task_Dispatcher_Access; Time : Duration := 0.01; Do_Work : Boolean := True; begin Log.Info ("Event consumer is ready"); select accept Start (D : in Task_Dispatcher_Access) do Dispatcher := D; end Start; Log.Info ("Event consumer is started"); while Do_Work loop declare Nb_Queues : constant Natural := Dispatcher.Queues.Get_Count; Queue : AWA.Events.Queues.Queue_Ref; Nb_Events : Natural := 0; Context : AWA.Services.Contexts.Service_Context; begin -- Set the service context. Context.Set_Context (Application => Dispatcher.Manager.Get_Application.all'Access, Principal => null); -- We can have several tasks that dispatch events from several queues. -- Each queue in the list must be given the same polling quota. -- Pick a queue and dispatch some pending events. -- Put back the queue in the fifo. for I in 1 .. Nb_Queues loop Dispatcher.Queues.Dequeue (Queue); begin Dispatcher.Dispatch (Queue, Nb_Events); exception when E : others => Log.Error ("Exception when dispatching events", E, True); end; Dispatcher.Queues.Enqueue (Queue); end loop; -- If we processed something, reset the timeout delay and continue polling. -- Otherwise, double the sleep time. if Nb_Events /= 0 then Time := 0.01; else Log.Debug ("Sleeping {0} seconds", Duration'Image (Time)); select accept Stop do Do_Work := False; end Stop; or accept Start (D : in Task_Dispatcher_Access) do Dispatcher := D; end Start; or delay Time; end select; if Time < 60.0 then Time := Time * 2.0; end if; end if; end; end loop; or terminate; end select; end Consumer; end AWA.Events.Dispatchers.Tasks;
Create the Service_Context instance for the lifetime of the event dispatching and not for the lifetime of the task
Create the Service_Context instance for the lifetime of the event dispatching and not for the lifetime of the task
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e01eb6eebc572923a148972fb15155f5b298d8cb
tools/druss-commands-ping.adb
tools/druss-commands-ping.adb
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- 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; with Bbox.API; with Druss.Gateways; with Ada.Strings.Unbounded; package body Druss.Commands.Ping is use Ada.Strings.Unbounded; -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is Box : Bbox.API.Client_Type; procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Id : constant String := Manager.Get (Name & ".id", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Box.Post ("hosts/" & Id, "action=ping"); end Ping_Device; begin if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then return; end if; Gateway.Refresh; Box.Set_Server (To_String (Gateway.IP)); Box.Login (To_String (Gateway.Passwd)); Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access); end Do_Ping; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Kind : constant String := Manager.Get (Name & ".devicetype", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".ping.average", "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access); delay 5.0; Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_ACTIVE, "Ping", 8); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Ping; -- ------------------------------ -- Execute a ping from the gateway to each device. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin Command.Do_Ping (Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "ping: Ask the Bbox to ping the devices"); Console.Notice (N_HELP, "Usage: ping {active | inactive}"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " active Ping the active devices only"); Console.Notice (N_HELP, " inative Ping the inactive devices only"); end Help; end Druss.Commands.Ping;
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- 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; with Bbox.API; with Druss.Gateways; with Ada.Strings.Unbounded; package body Druss.Commands.Ping is use Ada.Strings.Unbounded; -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is Box : Bbox.API.Client_Type; procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Id : constant String := Manager.Get (Name & ".id", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Box.Post ("hosts/" & Id, "action=ping"); end Ping_Device; begin if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then return; end if; Gateway.Refresh; Box.Set_Server (To_String (Gateway.IP)); Box.Login (To_String (Gateway.Passwd)); Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access); end Do_Ping; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Kind : constant String := Manager.Get (Name & ".devicetype", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); Print_Perf (Console, F_ACTIVE, Manager.Get (Name & ".ping.average", "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access); delay 5.0; Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_ACTIVE, "Ping", 15); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Ping; -- ------------------------------ -- Execute a ping from the gateway to each device. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin Command.Do_Ping (Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "ping: Ask the Bbox to ping the devices"); Console.Notice (N_HELP, "Usage: ping {active | inactive}"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " active Ping the active devices only"); Console.Notice (N_HELP, " inative Ping the inactive devices only"); end Help; end Druss.Commands.Ping;
Use the Print_Perf operation to report the ping performance
Use the Print_Perf operation to report the ping performance
Ada
apache-2.0
stcarrez/bbox-ada-api
0612ba7401f6185b1f03e6c4fe60eb7ec91ec3c2
src/asf-components-html-pages.adb
src/asf-components-html-pages.adb
----------------------------------------------------------------------- -- html-pages -- HTML Page Components -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Utils; -- The <b>Pages</b> package implements various components used when building an HTML page. -- package body ASF.Components.Html.Pages is BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Head Component -- ------------------------------ -- ------------------------------ -- Encode the HTML head element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("head"); UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML head element. Before closing the head, generate the resource -- links that have been queued for the head generation. -- ------------------------------ overriding procedure Encode_End (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("head"); end Encode_End; -- ------------------------------ -- Encode the HTML body element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("body"); UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML body element. Before closing the body, generate the inclusion -- of differed resources (pending javascript, inclusion of javascript files) -- ------------------------------ overriding procedure Encode_End (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("body"); end Encode_End; begin Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES); Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES); end ASF.Components.Html.Pages;
----------------------------------------------------------------------- -- html-pages -- HTML Page Components -- Copyright (C) 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Beans.Objects; with ASF.Utils; -- The <b>Pages</b> package implements various components used when building an HTML page. -- package body ASF.Components.Html.Pages is BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Head Component -- ------------------------------ -- ------------------------------ -- Encode the HTML head element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("head"); UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML head element. Before closing the head, generate the resource -- links that have been queued for the head generation. -- ------------------------------ overriding procedure Encode_End (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("head"); end Encode_End; -- ------------------------------ -- Encode the HTML body element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("body"); UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML body element. Before closing the body, generate the inclusion -- of differed resources (pending javascript, inclusion of javascript files) -- ------------------------------ overriding procedure Encode_End (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("body"); end Encode_End; -- ------------------------------ -- Encode the DOCTYPE element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIDoctype; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Write ("<!DOCTYPE "); Writer.Write (UI.Get_Attribute ("rootElement", Context, "")); declare Public : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "public"); System : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "system"); begin if not Util.Beans.Objects.Is_Null (Public) then Writer.Write (" PUBLIC """); Writer.Write (Public); Writer.Write ('"'); end if; if not Util.Beans.Objects.Is_Null (System) then Writer.Write (" """); Writer.Write (System); Writer.Write ('"'); end if; end; Writer.Write ('>'); end if; end Encode_Begin; begin Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES); Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES); end ASF.Components.Html.Pages;
Implement the UIDoctype component with the <!DOCTYPE> generation according to the <h:doctype> JSF 2.2 standard
Implement the UIDoctype component with the <!DOCTYPE> generation according to the <h:doctype> JSF 2.2 standard
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
88b00759576926d704e2b0b2d977d020c63cae55
src/dynamo.adb
src/dynamo.adb
----------------------------------------------------------------------- -- dynamo -- Ada Code Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Sax.Readers; use Sax.Readers; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada.Command_Line; with Util.Log.Loggers; with Gen.Generator; procedure DBMapper is use Ada; use Ada.Strings.Unbounded; use Ada.Command_Line; Release : constant String := "Dynamo Ada Generator 0.3, Stephane Carrez"; Copyright : constant String := "Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc."; ----------------- -- Output_File -- ----------------- -------------------------------------------------- -- Usage -------------------------------------------------- procedure Usage is use Ada.Text_IO; begin Put_Line (Release); Put_Line (Copyright); New_Line; Put ("Usage: "); Put (Command_Name); Put_Line (" [-v] [-o directory] [-t templates] model.xml"); Put_Line ("where:"); Put_Line (" -v Verbose"); Put_Line (" -q Query mode"); Put_Line (" -o directory Directory where the Ada mapping files are generated"); Put_Line (" -t templates Directory where the Ada templates are defined"); Put_Line (" -c dir Directory where the Ada templates and configurations are defined"); New_Line; Put_Line (" -h Requests this info."); New_Line; end Usage; File_Count : Natural := 0; Out_Dir : Unbounded_String; Config_Dir : Unbounded_String; Template_Dir : Unbounded_String; begin -- Parse the command line loop case Getopt ("o: t: c:") is when ASCII.Nul => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 't' => Template_Dir := To_Unbounded_String (Parameter & "/"); when 'c' => Config_Dir := To_Unbounded_String (Parameter & "/"); when others => null; end case; end loop; if Length (Config_Dir) = 0 then Config_Dir := To_Unbounded_String ("config/"); end if; -- Configure the logs Util.Log.Loggers.Initialize (To_String (Config_Dir) & "log4j.properties"); declare Generator : Gen.Generator.Handler; begin if Length (Out_Dir) > 0 then Gen.Generator.Set_Result_Directory (Generator, Out_Dir); end if; if Length (Template_Dir) > 0 then Gen.Generator.Set_Template_Directory (Generator, Template_Dir); end if; Gen.Generator.Initialize (Generator, Config_Dir); -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; Gen.Generator.Read_Model (Generator, Model_File); end; end loop; if File_Count = 0 then Usage; Set_Exit_Status (2); return; end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); -- Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_PACKAGE, "model"); -- Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_TABLE, "sql"); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when E : XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); end DBMapper;
----------------------------------------------------------------------- -- dynamo -- Ada Code Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Sax.Readers; use Sax.Readers; with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada.Command_Line; with Util.Log.Loggers; with Gen.Generator; procedure Dynamo is use Ada; use Ada.Strings.Unbounded; use Ada.Command_Line; Release : constant String := "Dynamo Ada Generator 0.3, Stephane Carrez"; Copyright : constant String := "Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc."; ----------------- -- Output_File -- ----------------- -------------------------------------------------- -- Usage -------------------------------------------------- procedure Usage is use Ada.Text_IO; begin Put_Line (Release); Put_Line (Copyright); New_Line; Put ("Usage: "); Put (Command_Name); Put_Line (" [-v] [-o directory] [-t templates] model.xml"); Put_Line ("where:"); Put_Line (" -v Verbose"); Put_Line (" -q Query mode"); Put_Line (" -o directory Directory where the Ada mapping files are generated"); Put_Line (" -t templates Directory where the Ada templates are defined"); Put_Line (" -c dir Directory where the Ada templates and configurations are defined"); New_Line; Put_Line (" -h Requests this info."); New_Line; end Usage; File_Count : Natural := 0; Out_Dir : Unbounded_String; Config_Dir : Unbounded_String; Template_Dir : Unbounded_String; begin -- Parse the command line loop case Getopt ("o: t: c:") is when ASCII.Nul => exit; when 'o' => Out_Dir := To_Unbounded_String (Parameter & "/"); when 't' => Template_Dir := To_Unbounded_String (Parameter & "/"); when 'c' => Config_Dir := To_Unbounded_String (Parameter & "/"); when others => null; end case; end loop; if Length (Config_Dir) = 0 then Config_Dir := To_Unbounded_String ("config/"); end if; -- Configure the logs Util.Log.Loggers.Initialize (To_String (Config_Dir) & "log4j.properties"); declare Generator : Gen.Generator.Handler; begin if Length (Out_Dir) > 0 then Gen.Generator.Set_Result_Directory (Generator, Out_Dir); end if; if Length (Template_Dir) > 0 then Gen.Generator.Set_Template_Directory (Generator, Template_Dir); end if; Gen.Generator.Initialize (Generator, Config_Dir); -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; Gen.Generator.Read_Model (Generator, Model_File); end; end loop; if File_Count = 0 then Usage; Set_Exit_Status (2); return; end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); -- Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_PACKAGE, "model"); -- Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_TABLE, "sql"); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when E : XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); end Dynamo;
Rename procedure
Rename procedure
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
e447926d25e613a305a8508b51d3c0bb11f92805
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 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 Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Get_Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return ADO.Databases.Connection_Status is begin if Database.Impl = null then return ADO.Databases.CLOSED; end if; return Database.Impl.Database.Get_Status; end Get_Status; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Get the database connection. -- ------------------------------ function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class is begin Check_Session (Database); return Database.Impl.Database; end Get_Connection; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Query); end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Get_Driver_Index); Stmt : Query_Statement := Database.Impl.Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index, False); begin return Database.Impl.Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Impl.Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); Object.Impl.Database.Close; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); return Database.Impl.Database.Create_Statement (Table); end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 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 Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Database.Value.Get_Driver_Index); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare Index : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Value.Get_Driver_Index; SQL : constant String := ADO.Queries.Get_SQL (Query, Index, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare Pos : constant ADO.Drivers.Driver_Index := Database.Impl.Database.Value.Get_Driver_Index; SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Pos); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Refactor the session management - Implement the Get_Driver function - Update the Create_Statement operation to use the databse connection instance directly and avoid using the ADO.Databases package and operations
Refactor the session management - Implement the Get_Driver function - Update the Create_Statement operation to use the databse connection instance directly and avoid using the ADO.Databases package and operations
Ada
apache-2.0
stcarrez/ada-ado
f64d39892199dc2f572567681ccfbcb6325398f5
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- 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 ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression is type Event_ELResolver is new EL.Contexts.Default.Default_ELResolver with null record; overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object is begin if Base /= null then return EL.Contexts.Default.Default_ELResolver (Resolver).Get_Value (Context, Base, Name); else return Util.Beans.Objects.To_Object (Plugin.Get_Config (To_String (Name), "")); end if; end Get_Value; Resolver : aliased Event_ELResolver; Context : EL.Contexts.Default.Default_Context; Value : constant String := Plugin.Get_Config (Name, Default); begin Context.Set_Resolver (Resolver'Unchecked_Access); return EL.Expressions.Reduce_Expression (EL.Expressions.Create_Expression (Value, Context), Context); exception when E : others => Log.Error ("Invalid parameter ", E, True); return EL.Expressions.Create_Expression ("", Context); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with Util.Properties; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module_Manager; Name : String; Default : String := "") return String is begin return Plugin.Module.all.Get_Config (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module_Manager; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Module.all.Get_Config (Config); end Get_Config; -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String is begin return Plugin.Config.Get (Config); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression is type Event_ELResolver is new EL.Contexts.Default.Default_ELResolver with null record; overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object is begin if Base /= null then return EL.Contexts.Default.Default_ELResolver (Resolver).Get_Value (Context, Base, Name); else return Util.Beans.Objects.To_Object (Plugin.Get_Config (To_String (Name), "")); end if; end Get_Value; Resolver : aliased Event_ELResolver; Context : EL.Contexts.Default.Default_Context; Value : constant String := Plugin.Get_Config (Name, Default); begin Context.Set_Resolver (Resolver'Unchecked_Access); return EL.Expressions.Reduce_Expression (EL.Expressions.Create_Expression (Value, Context), Context); exception when E : others => Log.Error ("Invalid parameter ", E, True); return EL.Expressions.Create_Expression ("", Context); end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is procedure Copy (Params : in Util.Properties.Manager'Class); procedure Copy (Params : in Util.Properties.Manager'Class) is begin Plugin.Config.Copy (From => Params, Prefix => Name & ".", Strip => True); end Copy; Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Info ("Module configuration file '{0}' does not exist", Path); end; Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration App.Get_Init_Parameters (Copy'Access); Plugin.Configure (Plugin.Config); exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. -- ------------------------------ procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)) is Iter : Module_Maps.Cursor := Registry.Name_Map.First; begin while Module_Maps.Has_Element (Iter) loop Process (Module_Maps.Element (Iter).all); Module_Maps.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. -- ------------------------------ procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Add_Listener (Into.Listeners, Item); end Add_Listener; -- ------------------------------ -- Find the module with the given name in the application and add the listener to the -- module listener list. -- ------------------------------ procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access) is M : constant Module_Access := Plugin.App.Find_Module (Name); begin if M = null then Log.Error ("Cannot find module {0} to add a lifecycle listener", Name); else M.Add_Listener (Item); end if; end Add_Listener; -- ------------------------------ -- Remove a listener from the module listener list. -- ------------------------------ procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access) is begin Util.Listeners.Remove_Listener (Into.Listeners, Item); end Remove_Listener; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
Implement Get_Config function for a Module_Manager type
Implement Get_Config function for a Module_Manager type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa