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
|
---|---|---|---|---|---|---|---|---|---|
1494491598fabdaa9f42ad95c681b6708bc74dae
|
arch/ARM/Nordic/drivers/nrf51-twi.adb
|
arch/ARM/Nordic/drivers/nrf51-twi.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with NRF51_SVD.TWI; use NRF51_SVD.TWI;
package body nRF51.TWI is
procedure Stop_Sequence (This : in out TWI_Master'Class);
-------------------
-- Stop_Sequence --
-------------------
procedure Stop_Sequence (This : in out TWI_Master'Class) is
begin
-- Stop sequence
This.Periph.EVENTS_STOPPED := 0;
This.Periph.TASKS_STOP := 1;
while This.Periph.EVENTS_STOPPED = 0 loop
null;
end loop;
end Stop_Sequence;
------------
-- Enable --
------------
procedure Enable (This : in out TWI_Master) is
begin
This.Periph.ENABLE.ENABLE := Enabled;
end Enable;
-------------
-- Disable --
-------------
procedure Disable (This : in out TWI_Master) is
begin
This.Periph.ENABLE.ENABLE := Disabled;
end Disable;
-------------
-- Enabled --
-------------
function Enabled (This : TWI_Master) return Boolean is
begin
return This.Periph.ENABLE.ENABLE = Enabled;
end Enabled;
---------------
-- Configure --
---------------
procedure Configure
(This : in out TWI_Master;
SCL, SDA : GPIO_Pin_Index;
Speed : TWI_Speed)
is
begin
This.Periph.PSELSCL := UInt32 (SCL);
This.Periph.PSELSDA := UInt32 (SDA);
This.Periph.FREQUENCY := (case Speed is
when TWI_100kbps => 16#0198_0000#,
when TWI_250kbps => 16#0400_0000#,
when TWI_400kbps => 16#0668_0000#);
end Configure;
----------------
-- Disconnect --
----------------
procedure Disconnect (This : in out TWI_Master) is
begin
This.Periph.PSELSCL := 16#FFFF_FFFF#;
This.Periph.PSELSDA := 16#FFFF_FFFF#;
end Disconnect;
---------------------
-- Master_Transmit --
---------------------
overriding procedure Master_Transmit
(This : in out TWI_Master;
Addr : I2C_Address;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
pragma Unreferenced (Timeout);
Index : Integer := Data'First + 1;
Evt_Err : UInt32;
Err_Src : ERRORSRC_Register with Unreferenced;
begin
if Data'Length = 0 then
Status := Ok;
return;
end if;
-- Clear errors
This.Periph.ERRORSRC.OVERRUN := Errorsrc_Overrun_Field_Reset;
This.Periph.ERRORSRC.ANACK := Errorsrc_Anack_Field_Reset;
This.Periph.ERRORSRC.DNACK := Errorsrc_Dnack_Field_Reset;
-- Set Address
This.Periph.ADDRESS.ADDRESS := UInt7 (Addr / 2);
-- Prepare first byte
This.Periph.TXD.TXD := Data (Data'First);
-- Start TX sequence
This.Periph.TASKS_STARTTX := 1;
loop
loop
Evt_Err := This.Periph.EVENTS_ERROR;
if Evt_Err /= 0 then
Err_Src := This.Periph.ERRORSRC;
Status := Err_Error;
-- Clear the error
This.Periph.EVENTS_ERROR := 0;
-- Stop sequence
This.Periph.TASKS_STOP := 1;
return;
end if;
exit when This.Periph.EVENTS_TXDSENT /= 0;
end loop;
-- Clear the event
This.Periph.EVENTS_TXDSENT := 0;
exit when Index > Data'Last;
This.Periph.TXD.TXD := Data (Index);
Index := Index + 1;
end loop;
if This.Do_Stop_Sequence then
Stop_Sequence (This);
end if;
Status := Ok;
end Master_Transmit;
--------------------
-- Master_Receive --
--------------------
overriding procedure Master_Receive
(This : in out TWI_Master;
Addr : I2C_Address;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
pragma Unreferenced (Timeout);
begin
if Data'Length = 0 then
Status := Ok;
return;
end if;
-- Clear errors
This.Periph.ERRORSRC.OVERRUN := Clear;
This.Periph.ERRORSRC.ANACK := Clear;
This.Periph.ERRORSRC.DNACK := Clear;
-- Set Address
This.Periph.ADDRESS.ADDRESS := UInt7 (Addr);
-- Configure SHORTS to automatically suspend TWI port when receiving a
-- byte.
This.Periph.SHORTS.BB_SUSPEND := Enabled;
This.Periph.SHORTS.BB_STOP := Disabled;
-- Start RX sequence
This.Periph.TASKS_STARTRX := 1;
for Index in Data'Range loop
loop
if This.Periph.EVENTS_ERROR /= 0 then
Status := Err_Error;
-- Clear the error
This.Periph.EVENTS_ERROR := 0;
Stop_Sequence (This);
return;
end if;
exit when This.Periph.EVENTS_RXDREADY /= 0;
end loop;
if Index = Data'Last and then This.Do_Stop_Sequence then
-- Configure SHORTS to automatically stop the TWI port and produce
-- a STOP event on the bus when receiving a byte.
This.Periph.SHORTS.BB_SUSPEND := Disabled;
This.Periph.SHORTS.BB_STOP := Enabled;
end if;
-- Clear the event
This.Periph.EVENTS_RXDREADY := 0;
Data (Index) := This.Periph.RXD.RXD;
end loop;
Status := Ok;
end Master_Receive;
---------------
-- Mem_Write --
---------------
overriding procedure Mem_Write
(This : in out TWI_Master;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
begin
This.Do_Stop_Sequence := False;
case Mem_Addr_Size is
when Memory_Size_8b =>
This.Master_Transmit (Addr => Addr,
Data => (0 => UInt8 (Mem_Addr)),
Status => Status,
Timeout => Timeout);
when Memory_Size_16b =>
This.Master_Transmit (Addr => Addr,
Data => (UInt8 (Shift_Right (Mem_Addr, 8)),
UInt8 (Mem_Addr and 16#FF#)),
Status => Status,
Timeout => Timeout);
end case;
This.Do_Stop_Sequence := True;
if Status /= Ok then
return;
end if;
This.Master_Transmit (Addr => Addr,
Data => Data,
Status => Status,
Timeout => Timeout);
end Mem_Write;
--------------
-- Mem_Read --
--------------
overriding procedure Mem_Read
(This : in out TWI_Master;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
begin
This.Do_Stop_Sequence := False;
case Mem_Addr_Size is
when Memory_Size_8b =>
This.Master_Transmit (Addr => Addr,
Data => (0 => UInt8 (Mem_Addr)),
Status => Status,
Timeout => Timeout);
when Memory_Size_16b =>
This.Master_Transmit (Addr => Addr,
Data => (UInt8 (Shift_Right (Mem_Addr, 8)),
UInt8 (Mem_Addr and 16#FF#)),
Status => Status,
Timeout => Timeout);
end case;
This.Do_Stop_Sequence := True;
if Status /= Ok then
return;
end if;
This.Master_Receive (Addr => Addr,
Data => Data,
Status => Status,
Timeout => Timeout);
end Mem_Read;
end nRF51.TWI;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with NRF51_SVD.TWI; use NRF51_SVD.TWI;
package body nRF51.TWI is
procedure Stop_Sequence (This : in out TWI_Master'Class);
-------------------
-- Stop_Sequence --
-------------------
procedure Stop_Sequence (This : in out TWI_Master'Class) is
begin
-- Stop sequence
This.Periph.EVENTS_STOPPED := 0;
This.Periph.TASKS_STOP := 1;
while This.Periph.EVENTS_STOPPED = 0 loop
null;
end loop;
end Stop_Sequence;
------------
-- Enable --
------------
procedure Enable (This : in out TWI_Master) is
begin
This.Periph.ENABLE.ENABLE := Enabled;
end Enable;
-------------
-- Disable --
-------------
procedure Disable (This : in out TWI_Master) is
begin
This.Periph.ENABLE.ENABLE := Disabled;
end Disable;
-------------
-- Enabled --
-------------
function Enabled (This : TWI_Master) return Boolean is
begin
return This.Periph.ENABLE.ENABLE = Enabled;
end Enabled;
---------------
-- Configure --
---------------
procedure Configure
(This : in out TWI_Master;
SCL, SDA : GPIO_Pin_Index;
Speed : TWI_Speed)
is
begin
This.Periph.PSELSCL := UInt32 (SCL);
This.Periph.PSELSDA := UInt32 (SDA);
This.Periph.FREQUENCY := (case Speed is
when TWI_100kbps => 16#0198_0000#,
when TWI_250kbps => 16#0400_0000#,
when TWI_400kbps => 16#0668_0000#);
end Configure;
----------------
-- Disconnect --
----------------
procedure Disconnect (This : in out TWI_Master) is
begin
This.Periph.PSELSCL := 16#FFFF_FFFF#;
This.Periph.PSELSDA := 16#FFFF_FFFF#;
end Disconnect;
---------------------
-- Master_Transmit --
---------------------
overriding procedure Master_Transmit
(This : in out TWI_Master;
Addr : I2C_Address;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
pragma Unreferenced (Timeout);
Index : Integer := Data'First + 1;
Evt_Err : UInt32;
Err_Src : ERRORSRC_Register with Unreferenced;
begin
if Data'Length = 0 then
Status := Ok;
return;
end if;
-- Clear errors
This.Periph.ERRORSRC := (Clear, Clear, Clear, 0);
-- Set Address
This.Periph.ADDRESS.ADDRESS := UInt7 (Addr / 2);
-- Prepare first byte
This.Periph.TXD.TXD := Data (Data'First);
-- Start TX sequence
This.Periph.TASKS_STARTTX := 1;
loop
loop
Evt_Err := This.Periph.EVENTS_ERROR;
if Evt_Err /= 0 then
Err_Src := This.Periph.ERRORSRC;
Status := Err_Error;
-- Clear the error
This.Periph.EVENTS_ERROR := 0;
-- Stop sequence
This.Periph.TASKS_STOP := 1;
return;
end if;
exit when This.Periph.EVENTS_TXDSENT /= 0;
end loop;
-- Clear the event
This.Periph.EVENTS_TXDSENT := 0;
exit when Index > Data'Last;
This.Periph.TXD.TXD := Data (Index);
Index := Index + 1;
end loop;
if This.Do_Stop_Sequence then
Stop_Sequence (This);
end if;
Status := Ok;
end Master_Transmit;
--------------------
-- Master_Receive --
--------------------
overriding procedure Master_Receive
(This : in out TWI_Master;
Addr : I2C_Address;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
pragma Unreferenced (Timeout);
begin
if Data'Length = 0 then
Status := Ok;
return;
end if;
-- Clear errors
This.Periph.ERRORSRC := (Clear, Clear, Clear, 0);
-- Set Address
This.Periph.ADDRESS.ADDRESS := UInt7 (Addr / 2);
if Data'Length = 1 then
-- Only one byte to receive so we stop at the next one
This.Periph.SHORTS.BB_STOP := Enabled;
This.Periph.SHORTS.BB_SUSPEND := Disabled;
else
-- Configure SHORTS to automatically suspend TWI port when receiving a
-- byte.
This.Periph.SHORTS.BB_SUSPEND := Enabled;
This.Periph.SHORTS.BB_STOP := Disabled;
end if;
-- Start RX sequence
This.Periph.TASKS_STARTRX := 1;
for Index in Data'Range loop
loop
if This.Periph.EVENTS_ERROR /= 0 then
Status := Err_Error;
-- Clear the error
This.Periph.EVENTS_ERROR := 0;
Stop_Sequence (This);
return;
end if;
exit when This.Periph.EVENTS_RXDREADY /= 0;
end loop;
-- Clear the event
This.Periph.EVENTS_RXDREADY := 0;
Data (Index) := This.Periph.RXD.RXD;
if Index = Data'Last - 1 and then This.Do_Stop_Sequence then
-- Configure SHORTS to automatically stop the TWI port and produce
-- a STOP event on the bus when receiving a byte.
This.Periph.SHORTS.BB_SUSPEND := Disabled;
This.Periph.SHORTS.BB_STOP := Enabled;
end if;
This.Periph.TASKS_RESUME := 1;
end loop;
Status := Ok;
end Master_Receive;
---------------
-- Mem_Write --
---------------
overriding procedure Mem_Write
(This : in out TWI_Master;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
begin
This.Do_Stop_Sequence := False;
case Mem_Addr_Size is
when Memory_Size_8b =>
This.Master_Transmit (Addr => Addr,
Data => (0 => UInt8 (Mem_Addr)),
Status => Status,
Timeout => Timeout);
when Memory_Size_16b =>
This.Master_Transmit (Addr => Addr,
Data => (UInt8 (Shift_Right (Mem_Addr, 8)),
UInt8 (Mem_Addr and 16#FF#)),
Status => Status,
Timeout => Timeout);
end case;
This.Do_Stop_Sequence := True;
if Status /= Ok then
This.Stop_Sequence;
return;
end if;
This.Master_Transmit (Addr => Addr,
Data => Data,
Status => Status,
Timeout => Timeout);
end Mem_Write;
--------------
-- Mem_Read --
--------------
overriding procedure Mem_Read
(This : in out TWI_Master;
Addr : I2C_Address;
Mem_Addr : UInt16;
Mem_Addr_Size : I2C_Memory_Address_Size;
Data : out I2C_Data;
Status : out I2C_Status;
Timeout : Natural := 1000)
is
begin
This.Do_Stop_Sequence := False;
case Mem_Addr_Size is
when Memory_Size_8b =>
This.Master_Transmit (Addr => Addr,
Data => (0 => UInt8 (Mem_Addr)),
Status => Status,
Timeout => Timeout);
when Memory_Size_16b =>
This.Master_Transmit (Addr => Addr,
Data => (UInt8 (Shift_Right (Mem_Addr, 8)),
UInt8 (Mem_Addr and 16#FF#)),
Status => Status,
Timeout => Timeout);
end case;
This.Do_Stop_Sequence := True;
if Status /= Ok then
This.Stop_Sequence;
return;
end if;
This.Master_Receive (Addr => Addr,
Data => Data,
Status => Status,
Timeout => Timeout);
end Mem_Read;
end nRF51.TWI;
|
Fix Master_Receive
|
nRF51.TWI: Fix Master_Receive
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
622516c6fc8dbb023384468cb2081334daae7d75
|
src/asf-servlets-faces-mappers.adb
|
src/asf-servlets-faces-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- Copyright (C) 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Routes.Servlets.Faces;
package body ASF.Servlets.Faces.Mappers is
use type ASF.Routes.Route_Type_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route;
begin
if Route = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
if not (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class) then
raise Util.Serialize.Mappers.Field_Error with "View " & View & " not mapped to a servlet";
end if;
return ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
To : ASF.Routes.Servlets.Faces.Faces_Route_Type_Access;
begin
if Route.Is_Null then
To := new ASF.Routes.Servlets.Faces.Faces_Route_Type;
To.View := To_Unbounded_String (View);
To.Servlet := Servlet;
Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access);
end if;
end Insert;
begin
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
ELContext => N.Context.all,
Process => Insert'Access);
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- Copyright (C) 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Servlet.Routes.Servlets;
with Servlet.Core;
with ASF.Routes;
package body ASF.Servlets.Faces.Mappers is
use type ASF.Routes.Route_Type_Access;
use type Servlet.Core.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Servlet.Core.Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Serv : constant Servlet_Access := Servlet.Core.Get_Servlet (Disp);
begin
if Serv = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
return Serv; -- Servlet.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
To : ASF.Routes.Faces_Route_Type_Access;
begin
if Route.Is_Null then
To := new ASF.Routes.Faces_Route_Type;
To.View := Ada.Strings.Unbounded.To_Unbounded_String (View);
To.Servlet := Servlet;
Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access);
end if;
end Insert;
begin
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
ELContext => N.Context.all,
Process => Insert'Access);
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
Package ASF.Servlets moved to Servlet.Core
|
Package ASF.Servlets moved to Servlet.Core
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
739a08471393d54364307c2bf8ada9037e3f53dd
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission",
Test_Add_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index",
Test_Add_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy",
Test_Read_Policy'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Returns true if the given permission is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Test_Principal;
Role : in Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Add_Permission and Get_Permission_Index
-- ------------------------------
procedure Test_Add_Permission (T : in out Test) is
Index1, Index2 : Permission_Index;
begin
Add_Permission ("test-create-permission", Index1);
T.Assert (Index1 = Get_Permission_Index ("test-create-permission"),
"Get_Permission_Index failed");
Add_Permission ("test-create-permission", Index2);
T.Assert (Index2 = Index1,
"Add_Permission failed");
end Test_Add_Permission;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Permissions.Permission_Manager;
Perm : Permission_Type;
User : Test_Principal;
begin
T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
end Test_Has_Permission;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Permissions.Permission_Manager;
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Role_Type;
Manager_Perm : Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, "empty.xml"));
M.Add_Role_Type (Name => "admin",
Result => Admin_Perm);
M.Add_Role_Type (Name => "manager",
Result => Manager_Perm);
M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml"));
User.Roles (Admin_Perm) := True;
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
P : constant URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
Permission => P), "Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
end;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
Permission => P), "Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Permissions.Permission_Manager;
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, File));
Admin_Perm := M.Find_Role (Role);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
declare
P : constant URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin_Perm) := True;
T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy",
Test_Read_Policy'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Returns true if the given permission is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Test_Principal;
Role : in Security.Policies.Roles.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
M.Add_Policy (R.all'Access);
M.Read_Policy (Util.Files.Compose (Path, "empty.xml"));
R.Add_Role_Type (Name => "admin",
Result => Admin_Perm);
R.Add_Role_Type (Name => "manager",
Result => Manager_Perm);
M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml"));
User.Roles (Admin_Perm) := True;
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
-- end;
--
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/list.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
-- end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (1);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, File));
--
-- Admin_Perm := M.Find_Role (Role);
--
-- Context.Set_Context (Manager => M'Unchecked_Access,
-- Principal => User'Unchecked_Access);
--
-- declare
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- -- A user without the role should not have the permission.
-- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was granted for user without role. URI=" & URI);
--
-- -- Set the role.
-- User.Roles (Admin_Perm) := True;
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was not granted for user with role. URI=" & URI);
-- end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Disable some unit tests
|
Disable some unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
6cd4bef8c6e4afea303a9d0054c2d4a8a89f4592
|
src/sys/os-win32/util-systems-constants.ads
|
src/sys/os-win32/util-systems-constants.ads
|
-- Generated by utildgen.c from system includes
with Interfaces.C;
package Util.Systems.Constants is
pragma Pure;
-- Flags used when opening a file with open/creat.
O_RDONLY : constant Interfaces.C.int := 8#000000#;
O_WRONLY : constant Interfaces.C.int := 8#000001#;
O_RDWR : constant Interfaces.C.int := 8#000002#;
O_CREAT : constant Interfaces.C.int := 8#000400#;
O_EXCL : constant Interfaces.C.int := 8#002000#;
O_TRUNC : constant Interfaces.C.int := 8#001000#;
O_APPEND : constant Interfaces.C.int := 8#000010#;
DLL_OPTIONS : constant String := "";
end Util.Systems.Constants;
|
-- Generated by utildgen.c from system includes
with Interfaces.C;
package Util.Systems.Constants is
pragma Pure;
-- Flags used when opening a file with open/creat.
O_RDONLY : constant Interfaces.C.int := 8#000000#;
O_WRONLY : constant Interfaces.C.int := 8#000001#;
O_RDWR : constant Interfaces.C.int := 8#000002#;
O_CREAT : constant Interfaces.C.int := 8#000400#;
O_EXCL : constant Interfaces.C.int := 8#002000#;
O_TRUNC : constant Interfaces.C.int := 8#001000#;
O_APPEND : constant Interfaces.C.int := 8#000010#;
DLL_OPTIONS : constant String := "";
SYMBOL_PREFIX : constant String := "";
end Util.Systems.Constants;
|
Declare SYMBOL_PREFIX
|
Declare SYMBOL_PREFIX
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d6cab7b521e80ccc9ae4e91de624a5ec198a0231
|
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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.Users.Models;
with AWA.Applications;
with AWA.Events.Services;
with ADO;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
package AC 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 AWA.Events.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 AC.Service_Context_Access := AC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
DB : ADO.Sessions.Master_Session := AC.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 AC.Service_Context_Access := AC.Current;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.SQL.Query;
Task_Id : constant Integer := 0;
-- ------------------------------
-- 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) 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;
-- Dispatch the event.
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;
Event : Module_Event;
begin
Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Msg.Get_Message_Type.Get_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;
Process (Event);
exception
when E : others =>
Log.Error ("Exception when processing event", 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);
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 ADO;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
package AC 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 AWA.Events.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 AC.Service_Context_Access := AC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
DB : ADO.Sessions.Master_Session := AC.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 AC.Service_Context_Access := AC.Current;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.SQL.Query;
Task_Id : constant Integer := 0;
-- ------------------------------
-- 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) 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;
-- Dispatch the event.
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;
Event : Module_Event;
begin
Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Msg.Get_Message_Type.Get_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;
Process (Event);
exception
when E : others =>
Log.Error ("Exception when processing event", 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);
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.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;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
859731f95acc372cbfa49dc209aa4fd7322fae3e
|
src/asf-security-filters.adb
|
src/asf-security-filters.adb
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- 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.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.Urls;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.Urls;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URI : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URI);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- 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.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.URLs;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URL : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URL_Permission (URL'Length)
:= URL_Permission '(Len => URL'Length, URL => URL);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URL);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
Update after changes in Security package
|
Update after changes in Security package
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b419b1ca2a466b7227ff2944408990de642d8bb7
|
src/asf-security-filters.adb
|
src/asf-security-filters.adb
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- 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.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.Urls;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.Urls;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URI : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URI);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- 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.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.URLs;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URL : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URL_Permission (URL'Length)
:= URL_Permission '(Len => URL'Length, URL => URL);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URL);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
Update after changes in Security package
|
Update after changes in Security package
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
bee0641e31cce09cfde2a6c2e25c1560417c75f2
|
src/gen-commands-project.adb
|
src/gen-commands-project.adb
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
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;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|proprietary] NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the GNU license or");
Put_Line (" a proprietary license. The author's name and email addresses");
Put_Line (" are also reported in generated files.");
end Help;
end Gen.Commands.Project;
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: -web -tool -ado") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|proprietary] [-web] [-tool] [-ado] "
& "NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the GNU license or");
Put_Line (" a proprietary license. The author's name and email addresses");
Put_Line (" are also reported in generated files.");
New_Line;
Put_Line (" -web Generate a Web application");
Put_Line (" -tool Generate a command line tool");
Put_Line (" -ado Generate a database tool operation for ADO");
end Help;
end Gen.Commands.Project;
|
Add new options to create-project command to generate command line applications, database applications or web applications
|
Add new options to create-project command to generate command line
applications, database applications or web applications
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
a73f748afa2b13fa711ea459c01880d8c997cc9e
|
regtests/util-streams-buffered-lzma-tests.ads
|
regtests/util-streams-buffered-lzma-tests.ads
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for LZMA buffered streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Streams.Buffered.Lzma.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Compress_Stream (T : in out Test);
procedure Test_Compress_File_Stream (T : in out Test);
end Util.Streams.Buffered.Lzma.Tests;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for LZMA buffered streams
-- Copyright (C) 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Streams.Buffered.Lzma.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Compress_Stream (T : in out Test);
procedure Test_Compress_File_Stream (T : in out Test);
procedure Test_Compress_Decompress_Stream (T : in out Test);
end Util.Streams.Buffered.Lzma.Tests;
|
Declare the Test_Compress_Decompress_Stream procedure
|
Declare the Test_Compress_Decompress_Stream procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
21182a3d70aec066d944f14f3492d310cc791323
|
src/security-permissions.adb
|
src/security-permissions.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Log.Loggers;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Permissions is
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Permissions");
-- A global map to translate a string to a permission index.
package Permission_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Permission_Index,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
protected type Global_Index is
-- Get the permission index
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Get the permission name associated with the index.
function Get_Name (Index : in Permission_Index) return String;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := NONE + 1;
end Global_Index;
protected body Global_Index is
function Get_Permission_Index (Name : in String) return Permission_Index is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
return Permission_Maps.Element (Pos);
else
raise Invalid_Name with "There is no permission '" & Name & "'";
end if;
end Get_Permission_Index;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Next_Index - 1;
end Get_Last_Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
Index := Permission_Maps.Element (Pos);
else
Index := Next_Index;
Log.Debug ("Creating permission index {1} for {0}",
Name, Permission_Index'Image (Index));
Map.Insert (Name, Index);
if Next_Index = Permission_Index'Last then
Log.Error ("Too many permission instantiated. "
& "Increase Security.Permissions.MAX_PERMISSION");
else
Next_Index := Next_Index + 1;
end if;
end if;
end Add_Permission;
-- ------------------------------
-- Get the permission name associated with the index.
-- ------------------------------
function Get_Name (Index : in Permission_Index) return String is
Iter : Permission_Maps.Cursor := Map.First;
begin
while Permission_Maps.Has_Element (Iter) loop
if Permission_Maps.Element (Iter) = Index then
return Permission_Maps.Key (Iter);
end if;
Permission_Maps.Next (Iter);
end loop;
return "";
end Get_Name;
end Global_Index;
Permission_Indexes : Global_Index;
-- ------------------------------
-- Get the permission index associated with the name.
-- ------------------------------
function Get_Permission_Index (Name : in String) return Permission_Index is
begin
return Permission_Indexes.Get_Permission_Index (Name);
end Get_Permission_Index;
-- ------------------------------
-- Get the permission name given the index.
-- ------------------------------
function Get_Name (Index : in Permission_Index) return String is
begin
return Permission_Indexes.Get_Name (Index);
end Get_Name;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Permission_Indexes.Get_Last_Permission_Index;
end Get_Last_Permission_Index;
-- ------------------------------
-- Add the permission name and allocate a unique permission index.
-- ------------------------------
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
begin
Permission_Indexes.Add_Permission (Name, Index);
end Add_Permission;
-- ------------------------------
-- Check if the permission index set contains the given permission index.
-- ------------------------------
function Has_Permission (Set : in Permission_Index_Set;
Index : in Permission_Index) return Boolean is
use Interfaces;
begin
return (Set (Natural (Index / 8)) and Shift_Left (1, Natural (Index mod 8))) /= 0;
end Has_Permission;
-- ------------------------------
-- Add the permission index to the set.
-- ------------------------------
procedure Add_Permission (Set : in out Permission_Index_Set;
Index : in Permission_Index) is
use Interfaces;
Pos : constant Natural := Natural (Index / 8);
begin
Set (Pos) := Set (Pos) or Shift_Left (1, Natural (Index mod 8));
end Add_Permission;
package body Definition is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Definition;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Util.Strings.Tokenizers;
with Util.Log.Loggers;
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package body Security.Permissions is
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Permissions");
-- A global map to translate a string to a permission index.
package Permission_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Permission_Index,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
protected type Global_Index is
-- Get the permission index
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Get the permission name associated with the index.
function Get_Name (Index : in Permission_Index) return String;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := NONE + 1;
end Global_Index;
protected body Global_Index is
function Get_Permission_Index (Name : in String) return Permission_Index is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
return Permission_Maps.Element (Pos);
else
raise Invalid_Name with "There is no permission '" & Name & "'";
end if;
end Get_Permission_Index;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Next_Index - 1;
end Get_Last_Permission_Index;
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
Pos : constant Permission_Maps.Cursor := Map.Find (Name);
begin
if Permission_Maps.Has_Element (Pos) then
Index := Permission_Maps.Element (Pos);
else
Index := Next_Index;
Log.Debug ("Creating permission index {1} for {0}",
Name, Permission_Index'Image (Index));
Map.Insert (Name, Index);
if Next_Index = Permission_Index'Last then
Log.Error ("Too many permission instantiated. "
& "Increase Security.Permissions.MAX_PERMISSION");
else
Next_Index := Next_Index + 1;
end if;
end if;
end Add_Permission;
-- ------------------------------
-- Get the permission name associated with the index.
-- ------------------------------
function Get_Name (Index : in Permission_Index) return String is
Iter : Permission_Maps.Cursor := Map.First;
begin
while Permission_Maps.Has_Element (Iter) loop
if Permission_Maps.Element (Iter) = Index then
return Permission_Maps.Key (Iter);
end if;
Permission_Maps.Next (Iter);
end loop;
return "";
end Get_Name;
end Global_Index;
Permission_Indexes : Global_Index;
-- ------------------------------
-- Get the permission index associated with the name.
-- ------------------------------
function Get_Permission_Index (Name : in String) return Permission_Index is
begin
return Permission_Indexes.Get_Permission_Index (Name);
end Get_Permission_Index;
function Occurence (List : in String; Of_Char : in Character) return Natural is
Count : Natural := 0;
begin
if List'Length > 0 then
Count := 1;
for C of List loop
if C = Of_Char then
Count := Count + 1;
end if;
end loop;
end if;
return Count;
end Occurence;
-- ------------------------------
-- Get the list of permissions whose name is given in the string with separated comma.
-- ------------------------------
function Get_Permission_Array (List : in String) return Permission_Index_Array is
Result : Permission_Index_Array (1 .. Occurence (List, ','));
Count : Natural := 0;
procedure Process (Name : in String;
Done : out Boolean) is
begin
Done := False;
Result (Count + 1) := Get_Permission_Index (Name);
Count := Count + 1;
exception
when Invalid_Name =>
Log.Info ("Permission {0} does not exist", Name);
end Process;
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => List,
Pattern => ",",
Process => Process'Access,
Going => Ada.Strings.Forward);
return Result (1 .. Count);
end Get_Permission_Array;
-- ------------------------------
-- Get the permission name given the index.
-- ------------------------------
function Get_Name (Index : in Permission_Index) return String is
begin
return Permission_Indexes.Get_Name (Index);
end Get_Name;
-- ------------------------------
-- Get the last permission index registered in the global permission map.
-- ------------------------------
function Get_Last_Permission_Index return Permission_Index is
begin
return Permission_Indexes.Get_Last_Permission_Index;
end Get_Last_Permission_Index;
-- ------------------------------
-- Add the permission name and allocate a unique permission index.
-- ------------------------------
procedure Add_Permission (Name : in String;
Index : out Permission_Index) is
begin
Permission_Indexes.Add_Permission (Name, Index);
end Add_Permission;
-- ------------------------------
-- Check if the permission index set contains the given permission index.
-- ------------------------------
function Has_Permission (Set : in Permission_Index_Set;
Index : in Permission_Index) return Boolean is
use Interfaces;
begin
return (Set (Natural (Index / 8)) and Shift_Left (1, Natural (Index mod 8))) /= 0;
end Has_Permission;
-- ------------------------------
-- Add the permission index to the set.
-- ------------------------------
procedure Add_Permission (Set : in out Permission_Index_Set;
Index : in Permission_Index) is
use Interfaces;
Pos : constant Natural := Natural (Index / 8);
begin
Set (Pos) := Set (Pos) or Shift_Left (1, Natural (Index mod 8));
end Add_Permission;
package body Definition is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Definition;
end Security.Permissions;
|
Implement the Get_Permission_Array function to split the string into tokens and lookup the permission and return them as an array
|
Implement the Get_Permission_Array function to split the string into tokens
and lookup the permission and return them as an array
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
6af76e4b802ecdf0005507084c7f94cba401f157
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- 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.
-----------------------------------------------------------------------
private with Interfaces;
-- == 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;
-- Max number of permissions supported by the implementation.
MAX_PERMISSION : constant Natural := 255;
type Permission_Index is new Natural range 0 .. MAX_PERMISSION;
NONE : constant Permission_Index := Permission_Index'First;
-- 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);
type Permission_Index_Set is private;
-- Check if the permission index set contains the given permission index.
function Has_Permission (Set : in Permission_Index_Set;
Index : in Permission_Index) return Boolean;
-- Add the permission index to the set.
procedure Add_Permission (Set : in out Permission_Index_Set;
Index : in Permission_Index);
-- The empty set of permission indexes.
EMPTY_SET : constant Permission_Index_Set;
private
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8;
type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8;
EMPTY_SET : constant Permission_Index_Set := (others => 0);
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- 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.
-----------------------------------------------------------------------
private with Interfaces;
-- == 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;
-- Max number of permissions supported by the implementation.
MAX_PERMISSION : constant Natural := 255;
type Permission_Index is new Natural range 0 .. MAX_PERMISSION;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
NONE : constant Permission_Index := Permission_Index'First;
-- 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);
type Permission_Index_Set is private;
-- Check if the permission index set contains the given permission index.
function Has_Permission (Set : in Permission_Index_Set;
Index : in Permission_Index) return Boolean;
-- Add the permission index to the set.
procedure Add_Permission (Set : in out Permission_Index_Set;
Index : in Permission_Index);
-- The empty set of permission indexes.
EMPTY_SET : constant Permission_Index_Set;
private
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8;
type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8;
EMPTY_SET : constant Permission_Index_Set := (others => 0);
end Security.Permissions;
|
Declare the Permission_Index_Array type
|
Declare the Permission_Index_Array type
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
df825c4460fecc4b190366bf5f2a05ec03f9b332
|
src/util-serialize-io.ads
|
src/util-serialize-io.ads
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Util.Beans.Objects;
with Util.Streams;
with Util.Streams.Buffered;
with Util.Log.Loggers;
package Util.Serialize.IO is
Parse_Error : exception;
-- ------------------------------
-- Output stream for serialization
-- ------------------------------
-- The <b>Output_Stream</b> interface defines the abstract operations for
-- the serialization framework to write objects on the stream according to
-- a target format such as XML or JSON.
type Output_Stream is limited interface and Util.Streams.Output_Stream;
-- Start a document.
procedure Start_Document (Stream : in out Output_Stream) is null;
-- Finish a document.
procedure End_Document (Stream : in out Output_Stream) is null;
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is null;
-- Write the attribute name/value pair.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
-- Write the entity value.
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is abstract;
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is abstract;
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Start_Array (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Array (Stream : in out Output_Stream;
Name : in String) is null;
type Reader is limited interface;
-- Start a document.
procedure Start_Document (Stream : in out Reader) is null;
-- Finish a document.
procedure End_Document (Stream : in out Reader) is null;
-- 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.
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is abstract;
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is abstract;
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is abstract;
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is abstract;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is abstract;
type Parser is abstract new Util.Log.Logging 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) is abstract;
-- Read the file and parse it using the parser.
procedure Parse (Handler : in out Parser;
File : in String;
Sink : in out Reader'Class);
-- Parse the content string.
procedure Parse_String (Handler : in out Parser;
Content : in String;
Sink : in out Reader'Class);
-- Returns true if the <b>Parse</b> operation detected at least one error.
function Has_Error (Handler : in Parser) return Boolean;
-- Set the error logger to report messages while parsing and reading the input file.
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
procedure Error (Handler : in out Parser;
Message : in String);
private
type Parser is abstract new Util.Log.Logging with record
Error_Flag : Boolean := False;
-- The file name to use when reporting errors.
File : Ada.Strings.Unbounded.Unbounded_String;
-- The logger which is used to report error messages when parsing an input file.
Error_Logger : Util.Log.Loggers.Logger_Access := null;
end record;
end Util.Serialize.IO;
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Util.Beans.Objects;
with Util.Streams;
with Util.Streams.Buffered;
with Util.Log.Loggers;
with Util.Nullables;
package Util.Serialize.IO is
Parse_Error : exception;
-- ------------------------------
-- Output stream for serialization
-- ------------------------------
-- The <b>Output_Stream</b> interface defines the abstract operations for
-- the serialization framework to write objects on the stream according to
-- a target format such as XML or JSON.
type Output_Stream is limited interface and Util.Streams.Output_Stream;
-- Start a document.
procedure Start_Document (Stream : in out Output_Stream) is null;
-- Finish a document.
procedure End_Document (Stream : in out Output_Stream) is null;
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is null;
-- Write the attribute name/value pair.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String) is abstract;
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
-- Write the entity value.
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String) is abstract;
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is abstract;
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is abstract;
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is abstract;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is abstract;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Start_Array (Stream : in out Output_Stream;
Name : in String) is null;
procedure End_Array (Stream : in out Output_Stream;
Name : in String) is null;
type Reader is limited interface;
-- Start a document.
procedure Start_Document (Stream : in out Reader) is null;
-- Finish a document.
procedure End_Document (Stream : in out Reader) is null;
-- 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.
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is abstract;
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is abstract;
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is abstract;
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is abstract;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is abstract;
type Parser is abstract new Util.Log.Logging 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) is abstract;
-- Read the file and parse it using the parser.
procedure Parse (Handler : in out Parser;
File : in String;
Sink : in out Reader'Class);
-- Parse the content string.
procedure Parse_String (Handler : in out Parser;
Content : in String;
Sink : in out Reader'Class);
-- Returns true if the <b>Parse</b> operation detected at least one error.
function Has_Error (Handler : in Parser) return Boolean;
-- Set the error logger to report messages while parsing and reading the input file.
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
procedure Error (Handler : in out Parser;
Message : in String);
private
type Parser is abstract new Util.Log.Logging with record
Error_Flag : Boolean := False;
-- The file name to use when reporting errors.
File : Ada.Strings.Unbounded.Unbounded_String;
-- The logger which is used to report error messages when parsing an input file.
Error_Logger : Util.Log.Loggers.Logger_Access := null;
end record;
end Util.Serialize.IO;
|
Declare Write_Attribute and Write_Entity for Nullable_String
|
Declare Write_Attribute and Write_Entity for Nullable_String
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e916afde9642cccd673112e87ac1f02ccaebb24a
|
regtests/asf-applications-views-tests.adb
|
regtests/asf-applications-views-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for ASF.Applications.Views
-- 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 Ada.Text_IO;
with ASF.Applications.Main;
with ASF.Applications.Views;
with ASF.Components.Core;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with EL.Contexts;
with EL.Contexts.Default;
with EL.Variables.Default;
with ASF.Contexts.Writer.Tests;
with Ada.Directories;
with Util.Tests;
with Util.Files;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use AUnit;
use Ada.Strings.Unbounded;
use ASF.Contexts.Writer.Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
use ASF;
use ASF.Contexts.Faces;
use EL.Contexts.Default;
use EL.Variables;
use EL.Variables.Default;
use EL.Contexts;
App : Applications.Main.Application;
-- H : Applications.Views.View_Handler;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
begin
Conf.Load_Properties ("regtests/view.properties");
App.Initialize (Conf);
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Rep : ASF.Responses.Mockup.Response;
Content : Unbounded_String;
-- Writer : aliased Test_Writer;
-- Context : aliased Faces_Context;
-- View : Components.Core.UIViewRoot;
-- ELContext : aliased EL.Contexts.Default.Default_Context;
-- Variables : aliased Default_Variable_Mapper;
-- Resolver : aliased Default_ELResolver;
begin
-- Context.Set_Response_Writer (Writer'Unchecked_Access);
-- Context.Set_ELContext (ELContext'Unchecked_Access);
-- ELContext.Set_Variable_Mapper (Variables'Unchecked_Access);
-- ELContext.Set_Resolver (Resolver'Unchecked_Access);
-- Writer.Initialize ("text/xml", "UTF-8", 16384);
-- Set_Current (Context'Unchecked_Access);
-- H.Restore_View (View_Name, Context, View);
--
-- H.Render_View (Context, View);
-- Writer.Flush;
App.Dispatch (Page => View_Name,
Request => Req,
Response => Rep);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Rep.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
end Test_Load_Facelet;
-- Test case name
overriding
function Name (T : Test) return Message_String is
begin
return Format ("Test " & To_String (T.Name));
end Name;
-- Perform the test.
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) = Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String (File_Path);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for ASF.Applications.Views
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with ASF.Applications.Main;
with ASF.Applications.Views;
with ASF.Components.Core;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with EL.Contexts;
with EL.Contexts.Default;
with EL.Variables.Default;
with ASF.Contexts.Writer.Tests;
with Ada.Directories;
with Util.Tests;
with Util.Files;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use AUnit;
use Ada.Strings.Unbounded;
use ASF.Contexts.Writer.Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
use ASF;
use ASF.Contexts.Faces;
use EL.Contexts.Default;
use EL.Variables;
use EL.Variables.Default;
use EL.Contexts;
App : Applications.Main.Application;
-- H : Applications.Views.View_Handler;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
App_Factory : Applications.Main.Application_Factory;
begin
Conf.Load_Properties ("regtests/view.properties");
App.Initialize (Conf, App_Factory);
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Rep : ASF.Responses.Mockup.Response;
Content : Unbounded_String;
begin
Req.Set_Method ("GET");
Req.Set_Path_Info (View_Name);
App.Dispatch (Page => View_Name,
Request => Req,
Response => Rep);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Rep.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
end Test_Load_Facelet;
-- Test case name
overriding
function Name (T : Test) return Message_String is
begin
return Format ("Test " & To_String (T.Name));
end Name;
-- Perform the test.
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) = Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String (File_Path);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
fix the unit test and cleanup
|
fix the unit test and cleanup
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
9869a1fd9dc0828b8f1cd9b5a137faf69c512d0e
|
src/orka/implementation/egl/orka-contexts-egl.adb
|
src/orka/implementation/egl/orka-contexts-egl.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Context;
with GL.Viewports;
with Orka.Loggers;
with Orka.Logging;
with EGL.Debug;
with EGL.Errors;
package body Orka.Contexts.EGL is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
procedure Print_Error
(Error : Standard.EGL.Errors.Error_Code;
Level : Standard.EGL.Debug.Severity;
Command, Message : String)
is
package Debug renames Standard.EGL.Debug;
Severity : constant Orka.Loggers.Severity :=
(case Level is
when Debug.Critical => Loggers.Error,
when Debug.Error => Loggers.Error,
when Debug.Warning => Loggers.Warning,
when Debug.Info => Loggers.Debug);
begin
Messages.Log (Severity, Error'Image & " in " & Command & ": " & Trim (Message));
end Print_Error;
procedure Print_Debug
(Display : Standard.EGL.Objects.Displays.Display;
Flags : Context_Flags) is
begin
Messages.Log (Debug, "Created EGL context");
Messages.Log (Debug, " platform: " & Display.Platform'Image);
declare
Name : constant String := Display.Device.Name;
begin
Messages.Log (Debug, " device: " & (if Name /= "" then Name else "unknown"));
end;
Messages.Log (Debug, " vendor: " & Display.Vendor);
Messages.Log (Debug, " version: " & Display.Version);
Messages.Log (Debug, " context:");
Messages.Log (Debug, " flags: " & Image (Flags));
Messages.Log (Debug, " version: " & GL.Context.Version_String);
Messages.Log (Debug, " renderer: " & GL.Context.Renderer);
end Print_Debug;
procedure Post_Initialize (Object : in out EGL_Context'Class) is
Flags : constant GL.Context.Context_Flags := GL.Context.Flags;
begin
Object.Version :=
(Major => GL.Context.Major_Version,
Minor => GL.Context.Minor_Version);
pragma Assert (Flags.Forward_Compatible);
Object.Flags.Debug := Flags.Debug;
Object.Flags.Robust := Flags.Robust_Access;
Object.Flags.No_Error := Flags.No_Error;
-- Other information about context can be read back as well with
-- GL.Context.Reset_Notification and GL.Context.Release_Behavior
GL.Viewports.Set_Clipping (GL.Viewports.Lower_Left, GL.Viewports.Zero_To_One);
Object.Vertex_Array.Create;
end Post_Initialize;
function Create_Context
(Device : Standard.EGL.Objects.Devices.Device;
Version : Context_Version;
Flags : Context_Flags := (others => False)) return Device_EGL_Context
is
package EGL_Contexts renames Standard.EGL.Objects.Contexts;
package EGL_Displays renames Standard.EGL.Objects.Displays;
begin
Standard.EGL.Debug.Set_Message_Callback (Print_Error'Access);
declare
Display : constant EGL_Displays.Display := EGL_Displays.Create_Display (Device);
begin
return Result : Device_EGL_Context do
Result.Context := EGL_Contexts.Create_Context (Display, Version, Flags);
Post_Initialize (Result);
Print_Debug (Display, Flags);
end return;
end;
end Create_Context;
overriding
function Create_Context
(Version : Context_Version;
Flags : Context_Flags := (others => False)) return Device_EGL_Context
is
package EGL_Devices renames Standard.EGL.Objects.Devices;
Devices : constant EGL_Devices.Device_List := EGL_Devices.Devices;
begin
Messages.Log (Debug, "EGL devices:");
for Device of Devices loop
declare
Name : constant String := Device.Name;
begin
Messages.Log (Debug, " - " & (if Name /= "" then Name else "unknown"));
end;
end loop;
return Create_Context (Devices (Devices'First), Version, Flags);
end Create_Context;
overriding
function Create_Context
(Version : Context_Version;
Flags : Context_Flags := (others => False)) return Wayland_EGL_Context is
begin
return Result : constant Wayland_EGL_Context :=
(Ada.Finalization.Limited_Controlled with others => <>)
do
-- EGL context for Wayland platform requires a pointer to a native
-- Wayland display
raise Program_Error;
end return;
end Create_Context;
function Create_Context
(Window : Standard.EGL.Native_Display_Ptr;
Version : Context_Version;
Flags : Context_Flags := (others => False)) return Wayland_EGL_Context
is
package EGL_Contexts renames Standard.EGL.Objects.Contexts;
package EGL_Displays renames Standard.EGL.Objects.Displays;
begin
Standard.EGL.Debug.Set_Message_Callback (Print_Error'Access);
declare
Display : constant EGL_Displays.Display := EGL_Displays.Create_Display (Window);
begin
return Result : Wayland_EGL_Context do
Result.Context := EGL_Contexts.Create_Context (Display, Version, Flags);
Result.Context.Make_Current;
Post_Initialize (Result);
Print_Debug (Display, Flags);
end return;
end;
end Create_Context;
overriding
procedure Finalize (Object : in out EGL_Context) is
begin
if Object.Flags.Debug then
Messages.Log (Debug, "Shutting down EGL");
end if;
Object.Vertex_Array.Delete;
end Finalize;
overriding
procedure Enable (Object : in out EGL_Context; Subject : Feature) is
begin
Contexts.Enable (Object.Features, Subject);
end Enable;
overriding
function Enabled (Object : EGL_Context; Subject : Feature) return Boolean
is (Contexts.Enabled (Object.Features, Subject));
overriding
procedure Make_Current (Object : Device_EGL_Context) is
begin
Object.Context.Make_Current;
end Make_Current;
overriding
procedure Make_Not_Current (Object : Device_EGL_Context) is
begin
Object.Context.Make_Not_Current;
end Make_Not_Current;
overriding
procedure Make_Current (Object : Wayland_EGL_Context) is
begin
Object.Context.Make_Current;
end Make_Current;
overriding
procedure Make_Not_Current (Object : Wayland_EGL_Context) is
begin
Object.Context.Make_Not_Current;
end Make_Not_Current;
end Orka.Contexts.EGL;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Context;
with GL.Viewports;
with Orka.Loggers;
with Orka.Logging;
with EGL.Debug;
with EGL.Errors;
package body Orka.Contexts.EGL is
use all type Orka.Logging.Source;
use all type Orka.Logging.Severity;
use Orka.Logging;
package Messages is new Orka.Logging.Messages (Window_System);
procedure Print_Error
(Error : Standard.EGL.Errors.Error_Code;
Level : Standard.EGL.Debug.Severity;
Command, Message : String)
is
package Debug renames Standard.EGL.Debug;
Severity : constant Orka.Loggers.Severity :=
(case Level is
when Debug.Critical => Loggers.Error,
when Debug.Error => Loggers.Error,
when Debug.Warning => Loggers.Warning,
when Debug.Info => Loggers.Debug);
begin
Messages.Log (Severity, Error'Image & " in " & Command & ": " & Trim (Message));
end Print_Error;
procedure Print_Debug
(Display : Standard.EGL.Objects.Displays.Display;
Flags : Context_Flags) is
begin
Messages.Log (Debug, "Created EGL context");
Messages.Log (Debug, " platform: " & Display.Platform'Image);
declare
Name : constant String := Display.Device.Name;
begin
Messages.Log (Debug, " device: " & (if Name /= "" then Name else "unknown"));
end;
Messages.Log (Debug, " vendor: " & Display.Vendor);
Messages.Log (Debug, " version: " & Display.Version);
Messages.Log (Debug, " context:");
Messages.Log (Debug, " flags: " & Image (Flags));
Messages.Log (Debug, " version: " & GL.Context.Version_String);
Messages.Log (Debug, " renderer: " & GL.Context.Renderer);
end Print_Debug;
procedure Post_Initialize (Object : in out EGL_Context'Class) is
Flags : constant GL.Context.Context_Flags := GL.Context.Flags;
begin
Object.Version :=
(Major => GL.Context.Major_Version,
Minor => GL.Context.Minor_Version);
pragma Assert (Flags.Forward_Compatible);
Object.Flags.Debug := Flags.Debug;
Object.Flags.Robust := Flags.Robust_Access;
Object.Flags.No_Error := Flags.No_Error;
-- Other information about context can be read back as well with
-- GL.Context.Reset_Notification and GL.Context.Release_Behavior
GL.Viewports.Set_Clipping (GL.Viewports.Lower_Left, GL.Viewports.Zero_To_One);
Object.Vertex_Array.Create;
end Post_Initialize;
function Create_Context
(Device : Standard.EGL.Objects.Devices.Device;
Version : Context_Version;
Flags : Context_Flags := (others => False)) return Device_EGL_Context
is
package EGL_Contexts renames Standard.EGL.Objects.Contexts;
package EGL_Displays renames Standard.EGL.Objects.Displays;
begin
Standard.EGL.Debug.Set_Message_Callback (Print_Error'Access);
declare
Display : constant EGL_Displays.Display := EGL_Displays.Create_Display (Device);
begin
return Result : Device_EGL_Context do
Result.Context := EGL_Contexts.Create_Context (Display, Version, Flags);
Result.Context.Make_Current;
Post_Initialize (Result);
Print_Debug (Display, Flags);
end return;
end;
end Create_Context;
overriding
function Create_Context
(Version : Context_Version;
Flags : Context_Flags := (others => False)) return Device_EGL_Context
is
package EGL_Devices renames Standard.EGL.Objects.Devices;
Devices : constant EGL_Devices.Device_List := EGL_Devices.Devices;
begin
Messages.Log (Debug, "EGL devices:");
for Device of Devices loop
declare
Name : constant String := Device.Name;
begin
Messages.Log (Debug, " - " & (if Name /= "" then Name else "unknown"));
end;
end loop;
return Create_Context (Devices (Devices'First), Version, Flags);
end Create_Context;
overriding
function Create_Context
(Version : Context_Version;
Flags : Context_Flags := (others => False)) return Wayland_EGL_Context is
begin
return Result : constant Wayland_EGL_Context :=
(Ada.Finalization.Limited_Controlled with others => <>)
do
-- EGL context for Wayland platform requires a pointer to a native
-- Wayland display
raise Program_Error;
end return;
end Create_Context;
function Create_Context
(Window : Standard.EGL.Native_Display_Ptr;
Version : Context_Version;
Flags : Context_Flags := (others => False)) return Wayland_EGL_Context
is
package EGL_Contexts renames Standard.EGL.Objects.Contexts;
package EGL_Displays renames Standard.EGL.Objects.Displays;
begin
Standard.EGL.Debug.Set_Message_Callback (Print_Error'Access);
declare
Display : constant EGL_Displays.Display := EGL_Displays.Create_Display (Window);
begin
return Result : Wayland_EGL_Context do
Result.Context := EGL_Contexts.Create_Context (Display, Version, Flags);
Result.Context.Make_Current;
Post_Initialize (Result);
Print_Debug (Display, Flags);
end return;
end;
end Create_Context;
overriding
procedure Finalize (Object : in out EGL_Context) is
begin
if Object.Flags.Debug then
Messages.Log (Debug, "Shutting down EGL");
end if;
Object.Vertex_Array.Delete;
end Finalize;
overriding
procedure Enable (Object : in out EGL_Context; Subject : Feature) is
begin
Contexts.Enable (Object.Features, Subject);
end Enable;
overriding
function Enabled (Object : EGL_Context; Subject : Feature) return Boolean
is (Contexts.Enabled (Object.Features, Subject));
overriding
procedure Make_Current (Object : Device_EGL_Context) is
begin
Object.Context.Make_Current;
end Make_Current;
overriding
procedure Make_Not_Current (Object : Device_EGL_Context) is
begin
Object.Context.Make_Not_Current;
end Make_Not_Current;
overriding
procedure Make_Current (Object : Wayland_EGL_Context) is
begin
Object.Context.Make_Current;
end Make_Current;
overriding
procedure Make_Not_Current (Object : Wayland_EGL_Context) is
begin
Object.Context.Make_Not_Current;
end Make_Not_Current;
end Orka.Contexts.EGL;
|
Fix reading back GL state if EGL context uses 'device' platform
|
orka: Fix reading back GL state if EGL context uses 'device' platform
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
af5e84c1b09712540025ca4fc1f9f5c6d223f5d9
|
src/base/log/util-log-appenders-files.ads
|
src/base/log/util-log-appenders-files.ads
|
-----------------------------------------------------------------------
-- util-log-appenders-files -- File log appenders
-- Copyright (C) 2001 - 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Util.Properties;
-- === File appender ===
-- The `File` appender recognises the following configurations:
--
-- | Name | Description |
-- | -------------- | -------------------------------------------------------------- |
-- | layout | Defines the format of the message printed by the appender. |
-- | level | Defines the minimum level above which messages are printed. |
-- | File | The path used by the appender to create the output file. |
-- | append | When 'true' or '1', the file is opened in append mode otherwise |
-- | | it is truncated (the default is to truncate). |
-- | immediateFlush | When 'true' or '1', the file is flushed after each message log. |
-- | | Immediate flush is useful in some situations to have the log file |
-- | | updated immediately at the expense of slowing down the processing |
-- | | of logs. |
package Util.Log.Appenders.Files is
-- ------------------------------
-- File appender
-- ------------------------------
type File_Appender (Length : Positive) is new Appender with private;
type File_Appender_Access is access all File_Appender'Class;
overriding
procedure Append (Self : in out File_Appender;
Message : in Util.Strings.Builders.Builder;
Date : in Ada.Calendar.Time;
Level : in Level_Type;
Logger : in String);
-- Set the file where the appender will write the logs.
-- When <tt>Append</tt> is true, the log message are appended to the existing file.
-- When set to false, the file is cleared before writing new messages.
procedure Set_File (Self : in out File_Appender;
Path : in String;
Append : in Boolean := True);
-- Flush the log events.
overriding
procedure Flush (Self : in out File_Appender);
-- Flush and close the file.
overriding
procedure Finalize (Self : in out File_Appender);
-- Create a file appender and configure it according to the properties
function Create (Name : in String;
Properties : in Util.Properties.Manager;
Default : in Level_Type)
return Appender_Access;
private
type File_Appender (Length : Positive) is new Appender (Length) with record
Output : Ada.Text_IO.File_Type;
Immediate_Flush : Boolean := False;
end record;
end Util.Log.Appenders.Files;
|
-----------------------------------------------------------------------
-- util-log-appenders-files -- File log appenders
-- Copyright (C) 2001 - 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Util.Properties;
-- === File appender ===
-- The `File` appender recognises the following configurations:
--
-- | Name | Description |
-- | -------------- | -------------------------------------------------------------- |
-- | layout | Defines the format of the message printed by the appender. |
-- | level | Defines the minimum level above which messages are printed. |
-- | File | The path used by the appender to create the output file. |
-- | append | When 'true' or '1', the file is opened in append mode otherwise |
-- | | it is truncated (the default is to truncate). |
-- | immediateFlush | When 'true' or '1', the file is flushed after each message log. |
-- | | Immediate flush is useful in some situations to have the log file |
-- | | updated immediately at the expense of slowing down the processing |
-- | | of logs. |
--
package Util.Log.Appenders.Files is
-- ------------------------------
-- File appender
-- ------------------------------
type File_Appender (Length : Positive) is new Appender with private;
type File_Appender_Access is access all File_Appender'Class;
overriding
procedure Append (Self : in out File_Appender;
Message : in Util.Strings.Builders.Builder;
Date : in Ada.Calendar.Time;
Level : in Level_Type;
Logger : in String);
-- Set the file where the appender will write the logs.
-- When <tt>Append</tt> is true, the log message are appended to the existing file.
-- When set to false, the file is cleared before writing new messages.
procedure Set_File (Self : in out File_Appender;
Path : in String;
Append : in Boolean := True);
-- Flush the log events.
overriding
procedure Flush (Self : in out File_Appender);
-- Flush and close the file.
overriding
procedure Finalize (Self : in out File_Appender);
-- Create a file appender and configure it according to the properties
function Create (Name : in String;
Properties : in Util.Properties.Manager;
Default : in Level_Type)
return Appender_Access;
private
type File_Appender (Length : Positive) is new Appender (Length) with record
Output : Ada.Text_IO.File_Type;
Immediate_Flush : Boolean := False;
end record;
end Util.Log.Appenders.Files;
|
Fix comment style
|
Fix comment style
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8776d1aff35af958942f7d2ebbe0f6f997bc42fd
|
src/gl/interface/gl-objects-buffers.ads
|
src/gl/interface/gl-objects-buffers.ads
|
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Interfaces.C.Pointers;
private with GL.Low_Level.Enums;
package GL.Objects.Buffers is
pragma Preelaborate;
function Minimum_Alignment return Types.Size
with Post => Minimum_Alignment'Result >= 64;
-- Minimum byte alignment of pointers returned by Map_Range
-- (at least 64 bytes to support SIMD CPU instructions)
type Access_Kind is (Read_Only, Write_Only, Read_Write);
type Access_Bits is record
Read : Boolean := False;
Write : Boolean := False;
Invalidate_Range : Boolean := False;
Invalidate_Buffer : Boolean := False;
Flush_Explicit : Boolean := False;
Unsynchronized : Boolean := False;
Persistent : Boolean := False;
Coherent : Boolean := False;
end record;
type Storage_Bits is record
Read : Boolean := False;
Write : Boolean := False;
Persistent : Boolean := False;
Coherent : Boolean := False;
Dynamic_Storage : Boolean := False;
Client_Storage : Boolean := False;
end record
with Dynamic_Predicate => (if Storage_Bits.Coherent then Storage_Bits.Persistent)
and (if Storage_Bits.Persistent then Storage_Bits.Read or Storage_Bits.Write);
type Buffer_Target (<>) is tagged limited private;
type Buffer is new GL_Object with private;
procedure Bind (Target : Buffer_Target; Object : Buffer'Class);
-- Bind the buffer object to the target
procedure Bind_Base (Target : Buffer_Target; Object : Buffer'Class; Index : Natural);
-- Bind the buffer object to the index of the target as well as to
-- the target itself.
--
-- Target must be one of the following:
--
-- * Atomic_Counter_Buffer
-- * Transform_Feedback_Buffer
-- * Uniform_Buffer
-- * Shader_Storage_Buffer
procedure Allocate (Object : Buffer; Number_Of_Elements : Long;
Kind : Numeric_Type; Storage_Flags : Storage_Bits);
-- Use this instead of Load_To_Immutable_Buffer when you don't want
-- to copy any data
function Current_Object (Target : Buffer_Target) return Buffer'Class;
function Access_Type (Object : Buffer) return Access_Kind;
function Immutable (Object : Buffer) return Boolean;
function Mapped (Object : Buffer) return Boolean;
function Size (Object : Buffer) return Long_Size;
function Storage_Flags (Object : Buffer) return Storage_Bits;
overriding
procedure Initialize_Id (Object : in out Buffer);
overriding
procedure Delete_Id (Object : in out Buffer);
overriding
function Identifier (Object : Buffer) return Types.Debug.Identifier is
(Types.Debug.Buffer);
procedure Unmap (Object : in out Buffer);
procedure Clear_With_Zeros (Object : Buffer);
procedure Invalidate_Data (Object : in out Buffer);
generic
with package Pointers is new Interfaces.C.Pointers (<>);
package Buffer_Pointers is
subtype Pointer is Pointers.Pointer;
procedure Bind_Range (Target : Buffer_Target; Object : Buffer'Class; Index : Natural;
Offset, Length : Types.Size);
-- Bind a part of the buffer object to the index of the target as
-- well as to the target itself.
--
-- Target must be one of the following:
--
-- * Atomic_Counter_Buffer
-- * Transform_Feedback_Buffer
-- * Uniform_Buffer
-- * Shader_Storage_Buffer
procedure Load_To_Immutable_Buffer (Object : Buffer;
Data : Pointers.Element_Array;
Storage_Flags : Storage_Bits);
procedure Map_Range (Object : in out Buffer; Access_Flags : Access_Bits;
Offset, Length : Types.Size;
Pointer : out Pointers.Pointer);
function Get_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset, Length : Types.Size) return Pointers.Element_Array
with Pre => Length > 0,
Post => Get_Mapped_Data'Result'Length = Length;
procedure Set_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset : Types.Size;
Data : Pointers.Element_Array)
with Pre => Data'Length > 0;
procedure Set_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset : Types.Size;
Value : Pointers.Element);
procedure Flush_Buffer_Range (Object : in out Buffer;
Offset, Length : Types.Size);
function To_Pointer (Object : Buffer) return Pointers.Pointer;
procedure Clear_Data
(Object : Buffer;
Kind : Numeric_Type;
Data : in out Pointers.Element_Array)
with Pre => Data'Length in 1 .. 4
and then Kind /= Double_Type
and then (if Data'Length = 3 then
Kind not in Byte_Type | UByte_Type | Short_Type | UShort_Type | Half_Type);
procedure Clear_Sub_Data
(Object : Buffer;
Offset, Length : Types.Size;
Kind : Numeric_Type;
Data : in out Pointers.Element_Array)
with Pre => Data'Length in 1 .. 4
and then Kind /= Double_Type
and then (if Data'Length = 3 then
Kind not in Byte_Type | UByte_Type | Short_Type | UShort_Type | Half_Type);
procedure Clear_With_Zeros (Object : Buffer; Offset, Length : Types.Size);
procedure Copy_Sub_Data (Object, Target_Object : Buffer;
Read_Offset, Write_Offset, Length : Types.Size);
procedure Set_Sub_Data (Object : Buffer;
Offset : Types.Size;
Data : in out Pointers.Element_Array);
procedure Get_Sub_Data (Object : Buffer;
Offset : Types.Size;
Data : out Pointers.Element_Array);
procedure Invalidate_Sub_Data (Object : Buffer;
Offset, Length : Types.Size);
end Buffer_Pointers;
Array_Buffer : constant Buffer_Target;
Element_Array_Buffer : constant Buffer_Target;
Pixel_Pack_Buffer : constant Buffer_Target;
Pixel_Unpack_Buffer : constant Buffer_Target;
Uniform_Buffer : constant Buffer_Target;
Texture_Buffer : constant Buffer_Target;
Transform_Feedback_Buffer : constant Buffer_Target;
Copy_Read_Buffer : constant Buffer_Target;
Copy_Write_Buffer : constant Buffer_Target;
Draw_Indirect_Buffer : constant Buffer_Target;
Parameter_Buffer : constant Buffer_Target;
Shader_Storage_Buffer : constant Buffer_Target;
Dispatch_Indirect_Buffer : constant Buffer_Target;
Query_Buffer : constant Buffer_Target;
Atomic_Counter_Buffer : constant Buffer_Target;
private
for Access_Kind use (Read_Only => 16#88B8#,
Write_Only => 16#88B9#,
Read_Write => 16#88BA#);
for Access_Kind'Size use Low_Level.Enum'Size;
for Access_Bits use record
Read at 0 range 0 .. 0;
Write at 0 range 1 .. 1;
Invalidate_Range at 0 range 2 .. 2;
Invalidate_Buffer at 0 range 3 .. 3;
Flush_Explicit at 0 range 4 .. 4;
Unsynchronized at 0 range 5 .. 5;
Persistent at 0 range 6 .. 6;
Coherent at 0 range 7 .. 7;
end record;
for Access_Bits'Size use Low_Level.Bitfield'Size;
for Storage_Bits use record
Read at 0 range 0 .. 0;
Write at 0 range 1 .. 1;
Persistent at 0 range 6 .. 6;
Coherent at 0 range 7 .. 7;
Dynamic_Storage at 0 range 8 .. 8;
Client_Storage at 0 range 9 .. 9;
end record;
for Storage_Bits'Size use Low_Level.Bitfield'Size;
type Buffer_Target (Kind : Low_Level.Enums.Buffer_Kind) is
tagged limited null record;
type Buffer is new GL_Object with null record;
Array_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Array_Buffer);
Element_Array_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Element_Array_Buffer);
Pixel_Pack_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Pixel_Pack_Buffer);
Pixel_Unpack_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Pixel_Unpack_Buffer);
Uniform_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Uniform_Buffer);
Texture_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Texture_Buffer);
Transform_Feedback_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Transform_Feedback_Buffer);
Copy_Read_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Copy_Read_Buffer);
Copy_Write_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Copy_Write_Buffer);
Draw_Indirect_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Draw_Indirect_Buffer);
Parameter_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Parameter_Buffer);
Shader_Storage_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Shader_Storage_Buffer);
Dispatch_Indirect_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Dispatch_Indirect_Buffer);
Query_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Query_Buffer);
Atomic_Counter_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Atomic_Counter_Buffer);
end GL.Objects.Buffers;
|
-- Copyright (c) 2012 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Interfaces.C.Pointers;
private with GL.Low_Level.Enums;
package GL.Objects.Buffers is
pragma Preelaborate;
function Minimum_Alignment return Types.Size
with Post => Minimum_Alignment'Result >= 64;
-- Minimum byte alignment of pointers returned by Map_Range
-- (at least 64 bytes to support SIMD CPU instructions)
type Access_Kind is (Read_Only, Write_Only, Read_Write);
type Access_Bits is record
Read : Boolean := False;
Write : Boolean := False;
Invalidate_Range : Boolean := False;
Invalidate_Buffer : Boolean := False;
Flush_Explicit : Boolean := False;
Unsynchronized : Boolean := False;
Persistent : Boolean := False;
Coherent : Boolean := False;
end record;
type Storage_Bits is record
Read : Boolean := False;
Write : Boolean := False;
Persistent : Boolean := False;
Coherent : Boolean := False;
Dynamic_Storage : Boolean := False;
Client_Storage : Boolean := False;
end record
with Dynamic_Predicate => (if Storage_Bits.Coherent then Storage_Bits.Persistent)
and (if Storage_Bits.Persistent then Storage_Bits.Read or Storage_Bits.Write);
type Buffer_Target (<>) is tagged limited private;
type Buffer is new GL_Object with private;
procedure Bind (Target : Buffer_Target; Object : Buffer'Class);
-- Bind the buffer object to the target
-- TODO Not one of the four targets used by Bind_Base
procedure Bind_Base (Target : Buffer_Target; Object : Buffer'Class; Index : Natural);
-- Bind the buffer object to the index of the target as well as to
-- the target itself.
--
-- Target must be one of the following:
--
-- * Atomic_Counter_Buffer
-- * Transform_Feedback_Buffer
-- * Uniform_Buffer
-- * Shader_Storage_Buffer
procedure Allocate (Object : Buffer; Number_Of_Elements : Long;
Kind : Numeric_Type; Storage_Flags : Storage_Bits);
-- Use this instead of Load_To_Immutable_Buffer when you don't want
-- to copy any data
function Current_Object (Target : Buffer_Target) return Buffer'Class;
function Access_Type (Object : Buffer) return Access_Kind;
function Immutable (Object : Buffer) return Boolean;
function Mapped (Object : Buffer) return Boolean;
function Size (Object : Buffer) return Long_Size;
function Storage_Flags (Object : Buffer) return Storage_Bits;
overriding
procedure Initialize_Id (Object : in out Buffer);
overriding
procedure Delete_Id (Object : in out Buffer);
overriding
function Identifier (Object : Buffer) return Types.Debug.Identifier is
(Types.Debug.Buffer);
procedure Unmap (Object : in out Buffer);
procedure Clear_With_Zeros (Object : Buffer);
procedure Invalidate_Data (Object : in out Buffer);
generic
with package Pointers is new Interfaces.C.Pointers (<>);
package Buffer_Pointers is
subtype Pointer is Pointers.Pointer;
procedure Bind_Range (Target : Buffer_Target; Object : Buffer'Class; Index : Natural;
Offset, Length : Types.Size);
-- Bind a part of the buffer object to the index of the target as
-- well as to the target itself.
--
-- Target must be one of the following:
--
-- * Atomic_Counter_Buffer
-- * Transform_Feedback_Buffer
-- * Uniform_Buffer
-- * Shader_Storage_Buffer
procedure Load_To_Immutable_Buffer (Object : Buffer;
Data : Pointers.Element_Array;
Storage_Flags : Storage_Bits);
procedure Map_Range (Object : in out Buffer; Access_Flags : Access_Bits;
Offset, Length : Types.Size;
Pointer : out Pointers.Pointer);
function Get_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset, Length : Types.Size) return Pointers.Element_Array
with Pre => Length > 0,
Post => Get_Mapped_Data'Result'Length = Length;
procedure Set_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset : Types.Size;
Data : Pointers.Element_Array)
with Pre => Data'Length > 0;
procedure Set_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset : Types.Size;
Value : Pointers.Element);
procedure Flush_Buffer_Range (Object : in out Buffer;
Offset, Length : Types.Size);
function To_Pointer (Object : Buffer) return Pointers.Pointer;
procedure Clear_Data
(Object : Buffer;
Kind : Numeric_Type;
Data : in out Pointers.Element_Array)
with Pre => Data'Length in 1 .. 4
and then Kind /= Double_Type
and then (if Data'Length = 3 then
Kind not in Byte_Type | UByte_Type | Short_Type | UShort_Type | Half_Type);
procedure Clear_Sub_Data
(Object : Buffer;
Offset, Length : Types.Size;
Kind : Numeric_Type;
Data : in out Pointers.Element_Array)
with Pre => Data'Length in 1 .. 4
and then Kind /= Double_Type
and then (if Data'Length = 3 then
Kind not in Byte_Type | UByte_Type | Short_Type | UShort_Type | Half_Type);
procedure Clear_With_Zeros (Object : Buffer; Offset, Length : Types.Size);
procedure Copy_Sub_Data (Object, Target_Object : Buffer;
Read_Offset, Write_Offset, Length : Types.Size);
procedure Set_Sub_Data (Object : Buffer;
Offset : Types.Size;
Data : in out Pointers.Element_Array);
procedure Get_Sub_Data (Object : Buffer;
Offset : Types.Size;
Data : out Pointers.Element_Array);
procedure Invalidate_Sub_Data (Object : Buffer;
Offset, Length : Types.Size);
end Buffer_Pointers;
-- Array_Buffer, Element_Array_Buffer, Texture_Buffer,
-- Copy_Read_Buffer, and Copy_Write_Buffer are no longer needed
-- since the GL.Objects.* packages use DSA
Pixel_Pack_Buffer : constant Buffer_Target;
Pixel_Unpack_Buffer : constant Buffer_Target;
Uniform_Buffer : constant Buffer_Target;
Transform_Feedback_Buffer : constant Buffer_Target;
Draw_Indirect_Buffer : constant Buffer_Target;
Parameter_Buffer : constant Buffer_Target;
Shader_Storage_Buffer : constant Buffer_Target;
Dispatch_Indirect_Buffer : constant Buffer_Target;
Query_Buffer : constant Buffer_Target;
Atomic_Counter_Buffer : constant Buffer_Target;
private
for Access_Kind use (Read_Only => 16#88B8#,
Write_Only => 16#88B9#,
Read_Write => 16#88BA#);
for Access_Kind'Size use Low_Level.Enum'Size;
for Access_Bits use record
Read at 0 range 0 .. 0;
Write at 0 range 1 .. 1;
Invalidate_Range at 0 range 2 .. 2;
Invalidate_Buffer at 0 range 3 .. 3;
Flush_Explicit at 0 range 4 .. 4;
Unsynchronized at 0 range 5 .. 5;
Persistent at 0 range 6 .. 6;
Coherent at 0 range 7 .. 7;
end record;
for Access_Bits'Size use Low_Level.Bitfield'Size;
for Storage_Bits use record
Read at 0 range 0 .. 0;
Write at 0 range 1 .. 1;
Persistent at 0 range 6 .. 6;
Coherent at 0 range 7 .. 7;
Dynamic_Storage at 0 range 8 .. 8;
Client_Storage at 0 range 9 .. 9;
end record;
for Storage_Bits'Size use Low_Level.Bitfield'Size;
type Buffer_Target (Kind : Low_Level.Enums.Buffer_Kind) is
tagged limited null record;
type Buffer is new GL_Object with null record;
Pixel_Pack_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Pixel_Pack_Buffer);
Pixel_Unpack_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Pixel_Unpack_Buffer);
Uniform_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Uniform_Buffer);
Transform_Feedback_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Transform_Feedback_Buffer);
Draw_Indirect_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Draw_Indirect_Buffer);
Parameter_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Parameter_Buffer);
Shader_Storage_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Shader_Storage_Buffer);
Dispatch_Indirect_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Dispatch_Indirect_Buffer);
Query_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Query_Buffer);
Atomic_Counter_Buffer : constant Buffer_Target
:= Buffer_Target'(Kind => Low_Level.Enums.Atomic_Counter_Buffer);
end GL.Objects.Buffers;
|
Remove some useless buffer binding targets
|
gl: Remove some useless buffer binding targets
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
f7364958375e084e85a12d35ad0046f14b4d9f73
|
awa/src/awa-commands-stop.adb
|
awa/src/awa-commands-stop.adb
|
-----------------------------------------------------------------------
-- awa-commands-stop -- Command to stop 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 GNAT.Sockets;
with Util.Streams.Sockets;
with Util.Streams.Texts;
package body AWA.Commands.Stop is
-- ------------------------------
-- 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"));
AWA.Commands.Setup (Config, Context);
end Setup;
-- ------------------------------
-- Stop the server by sending a 'stop' command on the management socket.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name, Args, Context);
Address : GNAT.Sockets.Sock_Addr_Type;
Stream : aliased Util.Streams.Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
begin
Address.Addr := GNAT.Sockets.Loopback_Inet_Addr;
Address.Port := GNAT.Sockets.Port_Type (Command.Management_Port);
Stream.Connect (Address);
Writer.Initialize (Stream'Access, 1024);
Writer.Write ("stop" & ASCII.CR & ASCII.LF);
Writer.Flush;
Writer.Close;
end Execute;
begin
Command_Drivers.Driver.Add_Command ("stop",
-("stop the web server"),
Command'Access);
end AWA.Commands.Stop;
|
-----------------------------------------------------------------------
-- awa-commands-stop -- Command to stop 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 GNAT.Sockets;
with Util.Streams.Sockets;
with Util.Streams.Texts;
package body AWA.Commands.Stop is
-- ------------------------------
-- 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"));
AWA.Commands.Setup_Command (Config, Context);
end Setup;
-- ------------------------------
-- Stop the server by sending a 'stop' command on the management socket.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name, Args, Context);
Address : GNAT.Sockets.Sock_Addr_Type;
Stream : aliased Util.Streams.Sockets.Socket_Stream;
Writer : Util.Streams.Texts.Print_Stream;
begin
Address.Addr := GNAT.Sockets.Loopback_Inet_Addr;
Address.Port := GNAT.Sockets.Port_Type (Command.Management_Port);
Stream.Connect (Address);
Writer.Initialize (Stream'Access, 1024);
Writer.Write ("stop" & ASCII.CR & ASCII.LF);
Writer.Flush;
Writer.Close;
end Execute;
begin
Command_Drivers.Driver.Add_Command ("stop",
-("stop the web server"),
Command'Access);
end AWA.Commands.Stop;
|
Rename procedure Setup into Setup_Command because it generates conflict bug in GNAT 2019
|
Rename procedure Setup into Setup_Command because it generates conflict bug in GNAT 2019
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
019bc15eb5f548f8e2c588f853def48fea7d914d
|
src/mysql/ado-drivers-connections-mysql.ads
|
src/mysql/ado-drivers-connections-mysql.ads
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- Copyright (C) 2009, 2010, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Mysql.Mysql; use Mysql.Mysql;
package ADO.Drivers.Connections.Mysql is
type Mysql_Driver is limited private;
-- Initialize the Mysql driver.
procedure Initialize;
private
-- Create a new MySQL connection using the configuration parameters.
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class);
type Mysql_Driver is new ADO.Drivers.Connections.Driver with record
Id : Natural := 0;
end record;
-- Deletes the Mysql driver.
overriding
procedure Finalize (D : in out Mysql_Driver);
-- Database connection implementation
type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record
Name : Unbounded_String := Null_Unbounded_String;
Server_Name : Unbounded_String := Null_Unbounded_String;
Login_Name : Unbounded_String := Null_Unbounded_String;
Password : Unbounded_String := Null_Unbounded_String;
Server : Mysql_Access := null;
Connected : Boolean := False;
-- MySQL autocommit flag
Autocommit : Boolean := True;
end record;
type Database_Connection_Access is access all Database_Connection'Class;
-- Get the database driver which manages this connection.
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access;
-- Create a delete statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access;
-- Create an insert statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access;
-- Create an update statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access;
-- Start a transaction.
overriding
procedure Begin_Transaction (Database : in out Database_Connection);
-- Commit the current transaction.
overriding
procedure Commit (Database : in out Database_Connection);
-- Rollback the current transaction.
overriding
procedure Rollback (Database : in out Database_Connection);
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String);
-- Closes the database connection
overriding
procedure Close (Database : in out Database_Connection);
overriding
procedure Finalize (Database : in out Database_Connection);
-- Load the database schema definition for the current database.
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition);
-- Create the database and initialize it with the schema SQL file.
overriding
procedure Create_Database (Database : in Database_Connection;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector);
end ADO.Drivers.Connections.Mysql;
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- Copyright (C) 2009, 2010, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Mysql.Mysql; use Mysql.Mysql;
package ADO.Drivers.Connections.Mysql is
type Mysql_Driver is limited private;
-- Initialize the Mysql driver.
procedure Initialize;
private
-- Create a new MySQL connection using the configuration parameters.
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class);
type Mysql_Driver is new ADO.Drivers.Connections.Driver with record
Id : Natural := 0;
end record;
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
overriding
procedure Create_Database (D : in out Mysql_Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector);
-- Deletes the Mysql driver.
overriding
procedure Finalize (D : in out Mysql_Driver);
-- Database connection implementation
type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record
Name : Unbounded_String := Null_Unbounded_String;
Server_Name : Unbounded_String := Null_Unbounded_String;
Login_Name : Unbounded_String := Null_Unbounded_String;
Password : Unbounded_String := Null_Unbounded_String;
Server : Mysql_Access := null;
Connected : Boolean := False;
-- MySQL autocommit flag
Autocommit : Boolean := True;
end record;
type Database_Connection_Access is access all Database_Connection'Class;
-- Get the database driver which manages this connection.
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access;
-- Create a delete statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access;
-- Create an insert statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access;
-- Create an update statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access;
-- Start a transaction.
overriding
procedure Begin_Transaction (Database : in out Database_Connection);
-- Commit the current transaction.
overriding
procedure Commit (Database : in out Database_Connection);
-- Rollback the current transaction.
overriding
procedure Rollback (Database : in out Database_Connection);
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String);
-- Closes the database connection
overriding
procedure Close (Database : in out Database_Connection);
overriding
procedure Finalize (Database : in out Database_Connection);
-- Load the database schema definition for the current database.
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition);
end ADO.Drivers.Connections.Mysql;
|
Move the Create_Database operation on the Driver instead of the database connection
|
Move the Create_Database operation on the Driver instead of the database connection
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
8cf5ab918679aedb7f491b23c09218b7a15a8673
|
jack-client.ads
|
jack-client.ads
|
with Ada.Containers.Ordered_Sets;
with Ada.Strings.Bounded;
with Ada.Unchecked_Deallocation;
with Jack.Thin;
with System;
pragma Elaborate_All (Jack.Thin);
package Jack.Client is
--
-- Types.
--
type Number_Of_Frames_t is new Thin.Number_Of_Frames_t;
--
-- Options
--
type Option_Selector_t is
(Do_Not_Start_Server,
Use_Exact_Name,
Server_Name,
Load_Name,
Load_Initialize);
type Options_t is array (Option_Selector_t) of Boolean;
--
-- Status
--
type Status_Selector_t is
(Failure,
Invalid_Option,
Name_Not_Unique,
Server_Started,
Server_Failed,
Server_Error,
No_Such_Client,
Load_Failure,
Init_Failure,
Shared_Memory_Failure,
Version_Error);
type Status_t is array (Status_Selector_t) of Boolean;
--
-- Port flags
--
type Port_Flag_Selector_t is
(Port_Is_Input,
Port_Is_Output,
Port_Is_Physical,
Port_Can_Monitor,
Port_Is_Terminal);
type Port_Flags_t is array (Port_Flag_Selector_t) of Boolean;
--
-- Client
--
type Client_t is limited private;
Invalid_Client : constant Client_t;
function Compare
(Left : in Client_t;
Right : in Client_t) return Boolean;
function "="
(Left : in Client_t;
Right : in Client_t) return Boolean renames Compare;
--
-- Port
--
type Port_t is limited private;
Invalid_Port : constant Port_t;
--
-- Port name
--
subtype Port_Name_Size_t is Natural range 0 .. Natural (Thin.Port_Name_Size);
subtype Port_Name_Index_t is Port_Name_Size_t range 1 .. Port_Name_Size_t'Last;
package Port_Names is new
Ada.Strings.Bounded.Generic_Bounded_Length (Port_Name_Index_t'Last);
subtype Port_Name_t is Port_Names.Bounded_String;
package Port_Name_Sets is new Ada.Containers.Ordered_Sets
(Element_Type => Port_Name_t,
"=" => Port_Names."=",
"<" => Port_Names."<");
subtype Port_Name_Set_t is Port_Name_Sets.Set;
--
-- API
--
-- proc_map : jack_client_close
procedure Close
(Client : in Client_t;
Failed : out Boolean);
-- proc_map : jack_connect
procedure Connect
(Client : in Client_t;
Source_Port : in Port_Name_t;
Destination_Port : in Port_Name_t;
Failed : out Boolean);
-- proc_map : jack_disconnect
procedure Disconnect
(Client : in Client_t;
Source_Port : in Port_Name_t;
Destination_Port : in Port_Name_t;
Failed : out Boolean);
-- proc_map : jack_client_open
procedure Open
(Client_Name : in String;
Options : in Options_t;
Client : out Client_t;
Status : in out Status_t);
Default_Audio_Type : constant String := "32 bit float mono audio";
-- proc_map : jack_port_register
procedure Port_Register
(Client : in Client_t;
Port : out Port_t;
Port_Name : in Port_Name_t;
Port_Type : in String;
Port_Flags : in Port_Flags_t;
Buffer_Size : in Natural := 0);
-- proc_map : jack_activate
procedure Activate
(Client : in Client_t;
Failed : out Boolean);
-- proc_map : jack_get_ports
procedure Get_Ports
(Client : in Client_t;
Port_Name_Pattern : in String;
Port_Type_Pattern : in String;
Port_Flags : in Port_Flags_t;
Ports : out Port_Name_Set_t);
generic
type User_Data_Type is private;
type User_Data_Access_Type is access User_Data_Type;
package Generic_Callbacks is
type Process_Callback_State_t is record
Callback : access procedure
(Number_Of_Frames : in Number_Of_Frames_t;
User_Data : in User_Data_Access_Type);
User_Data : User_Data_Access_Type;
end record;
type Process_Callback_State_Access_t is access Process_Callback_State_t;
procedure Deallocate_State is new Ada.Unchecked_Deallocation
(Object => User_Data_Type,
Name => User_Data_Access_Type);
-- proc_map : jack_set_process_callback
procedure Set_Process_Callback
(Client : in Client_t;
State : in Process_Callback_State_Access_t;
Failed : out Boolean);
end Generic_Callbacks;
--
-- Private
--
function To_Address (Client : in Client_t) return System.Address;
pragma Inline (To_Address);
function To_Address (Port : in Port_t) return System.Address;
pragma Inline (To_Address);
private
type Client_t is new System.Address;
type Port_t is new System.Address;
Invalid_Client : constant Client_t := Client_t (System.Null_Address);
Invalid_Port : constant Port_t := Port_t (System.Null_Address);
function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t;
pragma Inline (Map_Status_To_Thin);
function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t;
pragma Inline (Map_Thin_To_Status);
function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t;
pragma Inline (Map_Options_To_Thin);
function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t;
pragma Inline (Map_Thin_To_Options);
function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t;
pragma Inline (Map_Port_Flags_To_Thin);
function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t;
pragma Inline (Map_Thin_To_Port_Flags);
end Jack.Client;
|
with Ada.Containers.Ordered_Sets;
with Ada.Strings.Bounded;
with Ada.Strings;
with Ada.Unchecked_Deallocation;
with Jack.Thin;
with System;
pragma Elaborate_All (Jack.Thin);
package Jack.Client is
--
-- Types.
--
type Number_Of_Frames_t is new Thin.Number_Of_Frames_t;
--
-- Options
--
type Option_Selector_t is
(Do_Not_Start_Server,
Use_Exact_Name,
Server_Name,
Load_Name,
Load_Initialize);
type Options_t is array (Option_Selector_t) of Boolean;
--
-- Status
--
type Status_Selector_t is
(Failure,
Invalid_Option,
Name_Not_Unique,
Server_Started,
Server_Failed,
Server_Error,
No_Such_Client,
Load_Failure,
Init_Failure,
Shared_Memory_Failure,
Version_Error);
type Status_t is array (Status_Selector_t) of Boolean;
--
-- Port flags
--
type Port_Flag_Selector_t is
(Port_Is_Input,
Port_Is_Output,
Port_Is_Physical,
Port_Can_Monitor,
Port_Is_Terminal);
type Port_Flags_t is array (Port_Flag_Selector_t) of Boolean;
--
-- Client
--
type Client_t is limited private;
Invalid_Client : constant Client_t;
function Compare
(Left : in Client_t;
Right : in Client_t) return Boolean;
function "="
(Left : in Client_t;
Right : in Client_t) return Boolean renames Compare;
--
-- Port
--
type Port_t is limited private;
Invalid_Port : constant Port_t;
--
-- Port name
--
subtype Port_Name_Size_t is Natural range 0 .. Natural (Thin.Port_Name_Size);
subtype Port_Name_Index_t is Port_Name_Size_t range 1 .. Port_Name_Size_t'Last;
package Port_Names is new
Ada.Strings.Bounded.Generic_Bounded_Length (Port_Name_Index_t'Last);
function To_Port_Name
(Input : in String;
Drop : in Ada.Strings.Truncation := Ada.Strings.Error)
return Port_Names.Bounded_String renames Port_Names.To_Bounded_String;
subtype Port_Name_t is Port_Names.Bounded_String;
package Port_Name_Sets is new Ada.Containers.Ordered_Sets
(Element_Type => Port_Name_t,
"=" => Port_Names."=",
"<" => Port_Names."<");
subtype Port_Name_Set_t is Port_Name_Sets.Set;
--
-- API
--
-- proc_map : jack_client_close
procedure Close
(Client : in Client_t;
Failed : out Boolean);
-- proc_map : jack_connect
procedure Connect
(Client : in Client_t;
Source_Port : in Port_Name_t;
Destination_Port : in Port_Name_t;
Failed : out Boolean);
-- proc_map : jack_disconnect
procedure Disconnect
(Client : in Client_t;
Source_Port : in Port_Name_t;
Destination_Port : in Port_Name_t;
Failed : out Boolean);
-- proc_map : jack_client_open
procedure Open
(Client_Name : in String;
Options : in Options_t;
Client : out Client_t;
Status : in out Status_t);
Default_Audio_Type : constant String := "32 bit float mono audio";
-- proc_map : jack_port_register
procedure Port_Register
(Client : in Client_t;
Port : out Port_t;
Port_Name : in Port_Name_t;
Port_Type : in String;
Port_Flags : in Port_Flags_t;
Buffer_Size : in Natural := 0);
-- proc_map : jack_activate
procedure Activate
(Client : in Client_t;
Failed : out Boolean);
-- proc_map : jack_get_ports
procedure Get_Ports
(Client : in Client_t;
Port_Name_Pattern : in String;
Port_Type_Pattern : in String;
Port_Flags : in Port_Flags_t;
Ports : out Port_Name_Set_t);
generic
type User_Data_Type is private;
type User_Data_Access_Type is access User_Data_Type;
package Generic_Callbacks is
type Process_Callback_State_t is record
Callback : access procedure
(Number_Of_Frames : in Number_Of_Frames_t;
User_Data : in User_Data_Access_Type);
User_Data : User_Data_Access_Type;
end record;
type Process_Callback_State_Access_t is access Process_Callback_State_t;
procedure Deallocate_State is new Ada.Unchecked_Deallocation
(Object => User_Data_Type,
Name => User_Data_Access_Type);
-- proc_map : jack_set_process_callback
procedure Set_Process_Callback
(Client : in Client_t;
State : in Process_Callback_State_Access_t;
Failed : out Boolean);
end Generic_Callbacks;
--
-- Private
--
function To_Address (Client : in Client_t) return System.Address;
pragma Inline (To_Address);
function To_Address (Port : in Port_t) return System.Address;
pragma Inline (To_Address);
private
type Client_t is new System.Address;
type Port_t is new System.Address;
Invalid_Client : constant Client_t := Client_t (System.Null_Address);
Invalid_Port : constant Port_t := Port_t (System.Null_Address);
function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t;
pragma Inline (Map_Status_To_Thin);
function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t;
pragma Inline (Map_Thin_To_Status);
function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t;
pragma Inline (Map_Options_To_Thin);
function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t;
pragma Inline (Map_Thin_To_Options);
function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t;
pragma Inline (Map_Port_Flags_To_Thin);
function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t;
pragma Inline (Map_Thin_To_Port_Flags);
end Jack.Client;
|
Add to_port_name shorthand
|
Add to_port_name shorthand
|
Ada
|
isc
|
io7m/coreland-jack-ada,io7m/coreland-jack-ada
|
bc1982d7e3b0bac9b41c643cf4cf6ed6a88fcc99
|
src/security-openid.ads
|
src/security-openid.ads
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Security.Permissions;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- === Authentication process ==
-- The process is the following:
--
-- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the
-- OpenID return callback CB.
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
-- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication
-- URL for the association.
-- * The application should redirected the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Permissions.Principal with private;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Permissions.Role_Type) return Boolean;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- 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);
-- 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);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Permissions.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Security.Permissions;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- The authentication process is the following:
--
-- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the
-- OpenID return callback CB.
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
-- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication
-- URL for the association.
-- * The application should redirected the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- There are basically two steps that an application must implement.
--
-- == Step 1: creating the authentication URL ==
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenId manager, discover the OpenID provider,
-- associate with us and get an <b>End_Point</b>.
--
-- Mgr : Openid.Manager;
-- OP : Openid.End_Point;
-- Assoc : constant Association_Access := new Association;
--
-- The
--
-- Server.Initialize (Mgr);
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- == Step 2: verify the authentication in the callback URL ==
-- The second step is done when the user has finished the authentication successfully or not.
--
-- Mgr : Openid.Manager;
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Auth : Openid.Authentication;
-- Params : Auth_Params;
--
-- Server.Initialize (Mgr);
-- Mgr.Verify (Assoc.all, Params, Auth);
-- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure.
--
--
--
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Permissions.Principal with private;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Permissions.Role_Type) return Boolean;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- 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);
-- 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);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Permissions.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
Document the OpenID process
|
Document the OpenID process
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
ec5f7e4438de4cc2b20bef353412ac27be99a098
|
awa/plugins/awa-counters/src/awa-counters-beans.adb
|
awa/plugins/awa-counters/src/awa-counters-beans.adb
|
-----------------------------------------------------------------------
-- awa-counters-beans -- Counter bean definition
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Counters.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Counter_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Name);
begin
return Util.Beans.Objects.To_Object (From.Value);
end Get_Value;
end AWA.Counters.Beans;
|
-----------------------------------------------------------------------
-- awa-counters-beans -- Counter bean definition
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Dates.ISO8601;
with ADO.Queries.Loaders;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
package body AWA.Counters.Beans is
package ASC renames AWA.Services.Contexts;
function Parse_Date (Date : in String;
Now : in Ada.Calendar.Time) return Ada.Calendar.Time;
function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Counter_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Name);
begin
return Util.Beans.Objects.To_Object (From.Value);
end Get_Value;
overriding
function Get_Value (List : in Counter_Stat_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "stats" then
return Util.Beans.Objects.To_Object (Value => List.Stats_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Counters.Models.Stat_List_Bean (List).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Counter_Stat_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if not Util.Beans.Objects.Is_Empty (Value) then
AWA.Counters.Models.Stat_List_Bean (From).Set_Value (Name, Value);
end if;
end Set_Value;
function Get_Query (From : in Counter_Stat_Bean) return ADO.Queries.Query_Definition_Access is
Name : constant String := Ada.Strings.Unbounded.To_String (From.Query_Name);
begin
return ADO.Queries.Loaders.Find_Query (Name);
end Get_Query;
function Parse_Date (Date : in String;
Now : in Ada.Calendar.Time) return Ada.Calendar.Time is
use type Ada.Calendar.Time;
Day : Natural;
begin
if Date'Length = 0 or Date = "now" then
return Now;
elsif Date'Length > 5 and then Date (Date'First .. Date'First + 3) = "now-" then
Day := Natural'Value (Date (Date'First + 4 .. Date'Last));
return Now - Duration (Day * 86400);
else
return Util.Dates.ISO8601.Value (Date);
end if;
end Parse_Date;
-- ------------------------------
-- Load the statistics information.
-- ------------------------------
overriding
procedure Load (List : in out Counter_Stat_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
use type ADO.Identifier;
use type ADO.Queries.Query_Definition_Access;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Def : constant ADO.Queries.Query_Definition_Access := List.Get_Query;
Entity_Type : constant String := Ada.Strings.Unbounded.To_String (List.Entity_Type);
Session : ADO.Sessions.Session := List.Module.Get_Session;
Kind : ADO.Entity_Type;
First_Date : Ada.Calendar.Time;
Last_Date : Ada.Calendar.Time;
Query : ADO.Queries.Context;
begin
Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type);
First_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.First_Date), Now);
Last_Date := Parse_Date (Ada.Strings.Unbounded.To_String (List.Last_Date), Now);
if List.Entity_Id /= ADO.NO_IDENTIFIER and Def /= null then
Query.Set_Query (Def);
Query.Bind_Param ("entity_type", Kind);
Query.Bind_Param ("entity_id", List.Entity_Id);
Query.Bind_Param ("user_id", User);
Query.Bind_Param ("first_date", First_Date);
Query.Bind_Param ("last_date", Last_Date);
Query.Bind_Param ("counter_name", List.Counter_Name);
AWA.Counters.Models.List (List.Stats, Session, Query);
end if;
end Load;
-- ------------------------------
-- Create the Blog_Stat_Bean bean instance.
-- ------------------------------
function Create_Counter_Stat_Bean (Module : in AWA.Counters.Modules.Counter_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Counter_Stat_Bean_Access := new Counter_Stat_Bean;
begin
Object.Module := Module;
Object.Stats_Bean := Object.Stats'Access;
return Object.all'Access;
end Create_Counter_Stat_Bean;
end AWA.Counters.Beans;
|
Implement the Get_Value, Set_Value, Load and Create_Counter_Stat_Bean operations
|
Implement the Get_Value, Set_Value, Load and Create_Counter_Stat_Bean operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
fdcdcedefa2e8abd9430d889cff4d99ee8eb9c08
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
awa/plugins/awa-storages/src/awa-storages-beans.adb
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Objects.To_Object (From.Get_Folder.Get_Key);
end if;
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
begin
if Name = "folderId" then
Manager.Load_Folder (Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Bean.Set_Name (Part.Get_Name);
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- @method
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return Models.Storage_Info_List_Bean (List).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
Folder_Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter (FOLDER_ID_PARAMETER);
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Folder_Id = ADO.NO_IDENTIFIER then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Folder_Id);
end if;
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
-----------------------------------------------------------------------
-- awa-storages-beans -- Storage Ada Beans
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.Objects;
with ADO.Sessions.Entities;
with AWA.Helpers.Requests;
with AWA.Workspaces.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
package body AWA.Storages.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Upload_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "folderId" then
return ADO.Objects.To_Object (From.Get_Folder.Get_Key);
end if;
return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Upload_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager;
Folder : Models.Storage_Folder_Ref;
begin
if Name = "folderId" then
Manager.Load_Folder (Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
From.Set_Folder (Folder);
end if;
end Set_Value;
-- ------------------------------
-- Save the uploaded file in the storage service.
-- ------------------------------
procedure Save_Part (Bean : in out Upload_Bean;
Part : in ASF.Parts.Part'Class) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Bean.Set_Name (Part.Get_Name);
Bean.Set_Mime_Type (Part.Get_Content_Type);
Bean.Set_File_Size (Part.Get_Size);
Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE);
end Save_Part;
-- ------------------------------
-- Upload the file.
-- ------------------------------
procedure Upload (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Upload;
-- ------------------------------
-- Delete the file.
-- @method
-- ------------------------------
procedure Delete (Bean : in out Upload_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Delete (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Delete;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Folder_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if ADO.Objects.Is_Null (From) then
return Util.Beans.Objects.Null_Object;
else
return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Folder_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save (Bean : in out Folder_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager;
begin
Manager.Save_Folder (Bean);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success");
end Save;
overriding
function Get_Value (List : in Storage_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return Models.Storage_Info_List_Bean (List).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create the Folder_List_Bean bean instance.
-- ------------------------------
function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Folder_List_Bean;
-- ------------------------------
-- Create the Storage_List_Bean bean instance.
-- ------------------------------
function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Storages.Models;
use AWA.Services;
use type ADO.Identifier;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Object : constant Storage_List_Bean_Access := new Storage_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
Folder_Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter (FOLDER_ID_PARAMETER);
begin
Query.Set_Query (AWA.Storages.Models.Query_Storage_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, Session);
if Folder_Id = ADO.NO_IDENTIFIER then
Query.Bind_Null_Param ("folder_id");
else
Query.Bind_Param ("folder_id", Folder_Id);
end if;
AWA.Storages.Models.List (Object.all, Session, Query);
return Object.all'Access;
end Create_Storage_List_Bean;
end AWA.Storages.Beans;
|
Check that the folder instance is not null
|
Check that the folder instance is not null
|
Ada
|
apache-2.0
|
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
580ce835757c4fb2a7c81c9a408ac09e7579d3ac
|
awa/plugins/awa-tags/src/awa-tags-beans.ads
|
awa/plugins/awa-tags/src/awa-tags-beans.ads
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Finalization;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with Util.Beans.Lists.Strings;
with Util.Strings.Vectors;
with ADO;
with ADO.Utils;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Tags.Models;
with AWA.Tags.Modules;
-- == Tag Beans ==
-- Several bean types are provided to represent and manage a list of tags.
--
-- === Tag_List_Bean ===
-- The <tt>Tag_List_Bean</tt> holds a list of tags and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>questionTags</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>Awa_Question</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>question-edit</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the tags
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the tag. Such permission is
-- verified only when the <tt>awa:tagList</tt> component is used within a form.
--
-- === Tag_Search_Bean ===
-- The <tt>Tag_Search_Bean</tt> is dedicated to searching for tags that start with a given
-- pattern. The auto complete feature of the <tt>awa:tagList</tt> component can use this
-- bean type to look in the database for tags matching a start pattern. The declaration of the
-- bean should define the database table to search for tags associated with a given database
-- table. This is done in the XML configuration with the <tt>entity_type</tt> property.
--
-- <managed-bean>
-- <managed-bean-name>questionTagSearch</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Search_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- === Tag_Info_List_Bean ===
-- The <tt>Tag_Info_List_Bean</tt> holds a collection of tags with their weight. It is used
-- by the <tt>awa:tagCloud</tt> component.
--
-- <managed-bean>
-- <managed-bean-name>questionTagList</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Info_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
package AWA.Tags.Beans is
-- Compare two tags on their count and name.
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean;
package Tag_Ordered_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => AWA.Tags.Models.Tag_Info,
"=" => AWA.Tags.Models."=");
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_List_Bean_Access is access all Tag_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a tag on the entity.
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String);
-- Load the tags associated with the given database identifier.
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Set the list of tags to add.
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Set the list of tags to remove.
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier);
-- Create the tag list bean instance.
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Search_Bean_Access is access all Tag_Search_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Search the tags that match the search string.
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Create the tag search bean instance.
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Info_List_Bean_Access is access all Tag_Info_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of tags.
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session);
-- Create the tag info list bean instance.
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- The <tt>Entity_Tag_Map</tt> contains a list of tags associated with some entities.
-- It allows to retrieve from the database all the tags associated with several entities
-- and get the list of tags for a given entity.
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with private;
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access;
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object;
-- Release the list of tags.
procedure Clear (List : in out Entity_Tag_Map);
-- Load the list of tags associated with a list of entities.
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector);
-- Release the list of tags.
overriding
procedure Finalize (List : in out Entity_Tag_Map);
private
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
Added : Util.Strings.Vectors.Vector;
Deleted : Util.Strings.Vectors.Vector;
end record;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Entity_Tag_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => ADO.Identifier,
Element_Type => Util.Beans.Lists.Strings.List_Bean_Access,
Hash => ADO.Utils.Hash,
Equivalent_Keys => ADO."=",
"=" => Util.Beans.Lists.Strings."=");
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with record
Tags : Entity_Tag_Maps.Map;
end record;
end AWA.Tags.Beans;
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Finalization;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with Util.Beans.Lists.Strings;
with Util.Strings.Vectors;
with ADO;
with ADO.Utils;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Tags.Models;
with AWA.Tags.Modules;
-- == Tag Beans ==
-- Several bean types are provided to represent and manage a list of tags.
-- The tag module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- === Tag_List_Bean ===
-- The <tt>Tag_List_Bean</tt> holds a list of tags and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>questionTags</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>question-edit</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the tags
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the tag. Such permission is
-- verified only when the <tt>awa:tagList</tt> component is used within a form.
--
-- === Tag_Search_Bean ===
-- The <tt>Tag_Search_Bean</tt> is dedicated to searching for tags that start with a given
-- pattern. The auto complete feature of the <tt>awa:tagList</tt> component can use this
-- bean type to look in the database for tags matching a start pattern. The declaration of the
-- bean should define the database table to search for tags associated with a given database
-- table. This is done in the XML configuration with the <tt>entity_type</tt> property.
--
-- <managed-bean>
-- <managed-bean-name>questionTagSearch</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Search_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- === Tag_Info_List_Bean ===
-- The <tt>Tag_Info_List_Bean</tt> holds a collection of tags with their weight. It is used
-- by the <tt>awa:tagCloud</tt> component.
--
-- <managed-bean>
-- <managed-bean-name>questionTagList</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Info_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
package AWA.Tags.Beans is
-- Compare two tags on their count and name.
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean;
package Tag_Ordered_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => AWA.Tags.Models.Tag_Info,
"=" => AWA.Tags.Models."=");
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_List_Bean_Access is access all Tag_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a tag on the entity.
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String);
-- Load the tags associated with the given database identifier.
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Set the list of tags to add.
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Set the list of tags to remove.
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier);
-- Create the tag list bean instance.
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Search_Bean_Access is access all Tag_Search_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Search the tags that match the search string.
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Create the tag search bean instance.
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Info_List_Bean_Access is access all Tag_Info_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of tags.
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session);
-- Create the tag info list bean instance.
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- The <tt>Entity_Tag_Map</tt> contains a list of tags associated with some entities.
-- It allows to retrieve from the database all the tags associated with several entities
-- and get the list of tags for a given entity.
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with private;
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access;
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object;
-- Release the list of tags.
procedure Clear (List : in out Entity_Tag_Map);
-- Load the list of tags associated with a list of entities.
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector);
-- Release the list of tags.
overriding
procedure Finalize (List : in out Entity_Tag_Map);
private
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
Added : Util.Strings.Vectors.Vector;
Deleted : Util.Strings.Vectors.Vector;
end record;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Entity_Tag_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => ADO.Identifier,
Element_Type => Util.Beans.Lists.Strings.List_Bean_Access,
Hash => ADO.Utils.Hash,
Equivalent_Keys => ADO."=",
"=" => Util.Beans.Lists.Strings."=");
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with record
Tags : Entity_Tag_Maps.Map;
end record;
end AWA.Tags.Beans;
|
Fix comments and documentation
|
Fix comments and documentation
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
1c13deea6c1dfae735e71b40c7602ef80924e9a9
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an image.
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a quote.
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
end Wiki.Render.Html;
|
Rename Add_Image into Render_Image and update prototype
|
Rename Add_Image into Render_Image and update prototype
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
caa13a7c5d856b3cc52d9dd7db067f3493d685ef
|
demo/simple_2d.adb
|
demo/simple_2d.adb
|
-- Simple template program to allow viewing of 2D objects using OpenGL.
-- All setup is done already--just add the OpenGL code to draw the objects
-- below. You may also add any special initialization you need. Search
-- for the text "here:" to find the insertion points. The optimum viewing
-- area lies between -1 and +1 on both axes.
--
-- W. M. Richards, NiEstu, Phoenix AZ, January 2001
-- Ported to Lumen February 2011 by WMR
-- This code is covered by the GNU GPL, http://www.gnu.org/copyleft/gpl.html
--
-- Copyright 2001, 2011 W. M. Richards
-- Environment
with Ada.Characters.Latin_1;
with Ada.Text_IO;
with Lumen.Events;
with Lumen.Events.Animate;
with Lumen.Events.Keys;
with Lumen.Font.Txf;
with Lumen.GL;
with Lumen.GLU;
with Lumen.Image;
with Lumen.Window;
-- Enclosing procedure
procedure Simple_2D is
----------------------------------------------------------------------------
use Lumen; -- yes, we're definitely using Lumen
----------------------------------------------------------------------------
-- Constants
Win_Start : constant GL.SizeI := 500; -- in pixels; adjust to suit your scene's needs
-- Keystrokes we care about
Escape : constant Events.Key_Symbol := Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.ESC));
Letter_q : constant Events.Key_Symbol := Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.LC_Q));
---------------------------------------------------------------------------
-- App-specific exceptions
Program_Error : exception;
Program_Exit : exception;
----------------------------------------------------------------------------
-- Program variables
Win : Window.Window_Handle;
Curr_W : Natural := Win_Start;
Curr_H : Natural := Win_Start;
Aspect : GL.Double := GL.Double (Win_Start) / GL.Double (Win_Start);
StartX : GL.Double := 0.0;
StartY : GL.Double := 0.0;
RotC : GL.Double := 0.0;
Scale : GL.Double := 1.0;
XPan : GL.Double := 0.0;
YPan : GL.Double := 0.0;
Curr_RotC : GL.Double := 0.0;
Curr_Scale : GL.Double := 1.0;
Curr_XPan : GL.Double := 0.0;
Curr_YPan : GL.Double := 0.0;
Terminated : Boolean := False;
----------------------------------------------------------------------------
----- -----
----- L O C A L S -----
----- -----
----------------------------------------------------------------------------
-- Drop out of the main Gtk loop
procedure Finish is
begin -- Finish
Terminated := True;
end Finish;
----------------------------------------------------------------------------
-- Format a string showing current view status
function Sts_String return String is
package IntIO is new Ada.Text_IO.Integer_IO (integer);
package FltIO is new Ada.Text_IO.Float_IO (GL.Double);
Pad : String (1 .. 10) := " ";
XPanStr : String (1 .. 6);
YPanStr : String (1 .. 6);
RotCStr : String (1 .. 6);
SclStr : String (1 .. 6);
begin -- Sts_String
FltIO.Put (XPanStr, XPan, Aft => 2, Exp => 0);
FltIO.Put (YPanStr, YPan, Aft => 2, Exp => 0);
IntIO.Put (RotCStr, (360 - Integer (RotC)) mod 360);
FltIO.Put (SclStr, Scale, Aft => 2, Exp => 0);
return Pad & "Pan: (" & XPanStr & ", " & YPanStr & ") " &
Pad & "Rotation: " & RotCStr &
Pad & "Scale: " & SclStr;
end Sts_String;
----------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
begin -- Set_View
-- Set the globals used in some calculations
Curr_W := W;
Curr_H := H;
-- Viewport dimensions
GL.Viewport (0, 0, GL.SizeI (W), GL.SizeI (H));
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
GL.Matrix_Mode (GL.GL_PROJECTION);
GL.Load_Identity;
if W <= H then
Aspect := GL.Double (H) / GL.Double (W);
GLU.Ortho_2D (-2.0, 2.0, -2.0 * Aspect, 2.0 * Aspect);
else
Aspect := GL.Double (W) / GL.Double (H);
GLU.Ortho_2D (-2.0 * Aspect, 2.0 * Aspect, -2.0, 2.0);
end if;
end Set_View;
----------------------------------------------------------------------------
-- Update the drawing area
procedure Display is
------------------------------------------------------------------------
-- Local utility routine to draw a line segment
procedure Draw_Line (X1, Y1, X2, Y2 : in GL.Double) is
begin -- Draw_Line
GL.Begin_Primitive (GL.GL_LINES);
GL.Vertex (X1, Y1);
GL.Vertex (X2, Y2);
GL.End_Primitive;
end Draw_Line;
------------------------------------------------------------------------
-- Draw visible axes in space
procedure Draw_Axes is
begin -- Draw_Axes
GL.Color (Float (1.0), 0.0, 0.0, 1.0); Draw_Line (-1.0, 0.0, 1.0, 0.0);
GL.Color (Float (0.0), 1.0, 0.0, 1.0); Draw_Line ( 0.0, -1.0, 0.0, 1.0);
end Draw_Axes;
------------------------------------------------------------------------
begin -- Display
-- Clear to black (the default)
GL.Clear (GL.GL_COLOR_BUFFER_BIT);
-- Set up the viewing transforms
GL.Matrix_Mode (GL.GL_MODELVIEW);
GL.Load_Identity;
GL.Translate (XPan, YPan, 0.0);
GL.Scale (Scale, Scale, Scale);
GL.Rotate (RotC, 0.0, 0.0, 1.0);
-- Draw simple 2D axes
Draw_Axes;
GL.Flush;
-- Put the code to draw your objects here:
-- Swap the drawing we just did into the display area
Window.Swap (Win);
-- Update the status bar
end Display;
----------------------------------------------------------------------------
----- -----
----- C A L L B A C K S -----
----- -----
----------------------------------------------------------------------------
-- Callback triggered by the Resized event; tell OpenGL that the
-- user has resized the window
procedure Resize_Handler (Height : in Integer;
Width : in Integer) is
begin -- Resize_Handler
-- Set the new view parameters and redraw the scene
Set_View (Width, Height);
Display;
end Resize_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses
procedure Key_Handler (Category : in Events.Key_Category;
Symbol : in Events.Key_Symbol;
Modifiers : in Events.Modifier_Set) is
use type Events.Key_Symbol;
begin -- Key_Handler
case Symbol is
when Escape | Letter_q =>
Finish;
when Events.Keys.Home =>
RotC := 0.0;
Scale := 1.0;
XPan := 0.0;
YPan := 0.0;
Display;
when others =>
null;
end case;
end Key_Handler;
----------------------------------------------------------------------------
-- Mouse button has been pressed
procedure Button_Handler (X : in Integer;
Y : in Integer;
Button : in Window.Button_Enum;
Modifiers : in Events.Modifier_Set) is
use type Window.Button_Enum;
begin -- Button_Handler
-- Record starting position and current rotation/scale
StartX := GL.Double (X);
StartY := GL.Double (Curr_H - Y);
Curr_RotC := RotC;
Curr_Scale := Scale;
Curr_XPan := XPan;
Curr_YPan := YPan;
-- Handle mouse wheel events
if Button = Window.Button_4 then
Scale := Curr_Scale - 0.1;
Display;
elsif Button = Window.Button_5 then
Scale := Curr_Scale + 0.1;
Display;
end if;
end Button_Handler;
----------------------------------------------------------------------------
-- Mouse movement
procedure Drag_Handler (X : in Integer;
Y : in Integer;
Modifiers : in Events.Modifier_Set) is
Y_Prime : Integer := Curr_H - Y;
begin -- Drag_Handler
-- If it's a drag, update the figure parameters
if Modifiers (Events.Mod_Button_1) then
XPan := Curr_XPan + ((GL.Double (X) - StartX) / GL.Double (Curr_W));
YPan := Curr_YPan + ((GL.Double (Y) - StartY) / GL.Double (Curr_H));
Display;
elsif Modifiers (Events.Mod_Button_2) then
RotC := GL.Double (integer (Curr_RotC - ((GL.Double (X) - StartX) + (StartY - GL.Double (Y)))) mod 360);
Display;
elsif Modifiers (Events.Mod_Button_3) then
Scale := Curr_Scale + ((GL.Double (X) - StartX) / GL.Double (Curr_W)) -
((GL.Double (Y) - StartY) / GL.Double (Curr_H));
Display;
end if;
end Drag_Handler;
----------------------------------------------------------------------------
-- Re-draw the view
procedure Expose_Handler (Top : in Integer;
Left : in Integer;
Height : in Natural;
Width : in Natural) is
begin -- Expose_Handler
Display;
end Expose_Handler;
----------------------------------------------------------------------------
-- Called once per frame; just re-draws the scene
function New_Frame (Frame_Delta : in Duration) return Boolean is
begin -- New_Frame
Display;
return not Terminated;
end New_Frame;
----------------------------------------------------------------------------
----- -----
----- S E T U P -----
----- -----
----------------------------------------------------------------------------
-- Set up the main window and all its fiddly bits
procedure Init is
begin -- Init
-- Create the main window
Window.Create (Win,
Name => "2D Object Viewer",
Width => Win_Start,
Height => Win_Start);
Win.Exposed := Expose_Handler'Unrestricted_Access;
Win.Resize := Resize_Handler'Unrestricted_Access;
Win.Key_Press := Key_Handler'Unrestricted_Access;
Win.Mouse_Down := Button_Handler'Unrestricted_Access;
Win.Mouse_Move := Drag_Handler'Unrestricted_Access;
Set_View (Win_Start, Win_Start);
Display;
-- Create a packing box to stuff everything into
-- Create the OpenGL drawing area
-- Connect the event handlers
-- Put the OpenGL drawing area into the packing box
-- The status bar
-- The quit button
-- Put any one-time OpenGL initialization code here:
end Init;
-------------------------------------------------------------------------------
----- -----
----- M A I N -----
----- -----
-------------------------------------------------------------------------------
-- The main procedure
begin -- Simple_2D
Init;
-- Framerate assumed to be 24Hz
Lumen.Events.Animate.Run (Win, 24,New_Frame'Unrestricted_Access);
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Simple_2D;
|
-- Simple template program to allow viewing of 2D objects using OpenGL.
-- All setup is done already--just add the OpenGL code to draw the objects
-- below. You may also add any special initialization you need. Search
-- for the text "here:" to find the insertion points. The optimum viewing
-- area lies between -1 and +1 on both axes.
--
-- W. M. Richards, NiEstu, Phoenix AZ, January 2001
-- Ported to Lumen February 2011 by WMR
-- This code is covered by the GNU GPL, http://www.gnu.org/copyleft/gpl.html
--
-- Copyright 2001, 2011 W. M. Richards
-- Environment
with Ada.Characters.Latin_1;
with Ada.Text_IO;
with Lumen.Events;
with Lumen.Events.Animate;
with Lumen.Events.Keys;
with Lumen.Font.Txf;
with Lumen.GL;
with Lumen.GLU;
with Lumen.Image;
with Lumen.Window;
-- Enclosing procedure
procedure Simple_2D is
----------------------------------------------------------------------------
use Lumen; -- yes, we're definitely using Lumen
----------------------------------------------------------------------------
-- Constants
Win_Start : constant GL.SizeI := 500; -- in pixels; adjust to suit your scene's needs
-- Keystrokes we care about
Escape : constant Events.Key_Symbol := Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.ESC));
Letter_q : constant Events.Key_Symbol := Events.Key_Symbol (Character'Pos (Ada.Characters.Latin_1.LC_Q));
---------------------------------------------------------------------------
-- App-specific exceptions
Program_Error : exception;
Program_Exit : exception;
----------------------------------------------------------------------------
-- Program variables
Win : Window.Window_Handle;
Curr_W : Natural := Win_Start;
Curr_H : Natural := Win_Start;
Aspect : GL.Double := GL.Double (Win_Start) / GL.Double (Win_Start);
StartX : GL.Double := 0.0;
StartY : GL.Double := 0.0;
RotC : GL.Double := 0.0;
Scale : GL.Double := 1.0;
XPan : GL.Double := 0.0;
YPan : GL.Double := 0.0;
Curr_RotC : GL.Double := 0.0;
Curr_Scale : GL.Double := 1.0;
Curr_XPan : GL.Double := 0.0;
Curr_YPan : GL.Double := 0.0;
Terminated : Boolean := False;
----------------------------------------------------------------------------
----- -----
----- L O C A L S -----
----- -----
----------------------------------------------------------------------------
-- Drop out of the main Gtk loop
procedure Finish is
begin -- Finish
Terminated := True;
end Finish;
----------------------------------------------------------------------------
-- Format a string showing current view status
function Sts_String return String is
package IntIO is new Ada.Text_IO.Integer_IO (integer);
package FltIO is new Ada.Text_IO.Float_IO (GL.Double);
Pad : String (1 .. 10) := " ";
XPanStr : String (1 .. 6);
YPanStr : String (1 .. 6);
RotCStr : String (1 .. 6);
SclStr : String (1 .. 6);
begin -- Sts_String
FltIO.Put (XPanStr, XPan, Aft => 2, Exp => 0);
FltIO.Put (YPanStr, YPan, Aft => 2, Exp => 0);
IntIO.Put (RotCStr, (360 - Integer (RotC)) mod 360);
FltIO.Put (SclStr, Scale, Aft => 2, Exp => 0);
return Pad & "Pan: (" & XPanStr & ", " & YPanStr & ") " &
Pad & "Rotation: " & RotCStr &
Pad & "Scale: " & SclStr;
end Sts_String;
----------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
begin -- Set_View
-- Set the globals used in some calculations
Curr_W := W;
Curr_H := H;
-- Viewport dimensions
GL.Viewport (0, 0, GL.SizeI (W), GL.SizeI (H));
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
GL.Matrix_Mode (GL.GL_PROJECTION);
GL.Load_Identity;
if W <= H then
Aspect := GL.Double (H) / GL.Double (W);
GLU.Ortho_2D (-2.0, 2.0, -2.0 * Aspect, 2.0 * Aspect);
else
Aspect := GL.Double (W) / GL.Double (H);
GLU.Ortho_2D (-2.0 * Aspect, 2.0 * Aspect, -2.0, 2.0);
end if;
end Set_View;
----------------------------------------------------------------------------
-- Update the drawing area
procedure Display is
------------------------------------------------------------------------
-- Local utility routine to draw a line segment
procedure Draw_Line (X1, Y1, X2, Y2 : in GL.Double) is
begin -- Draw_Line
GL.Begin_Primitive (GL.GL_LINES);
GL.Vertex (X1, Y1);
GL.Vertex (X2, Y2);
GL.End_Primitive;
end Draw_Line;
------------------------------------------------------------------------
-- Draw visible axes in space
procedure Draw_Axes is
begin -- Draw_Axes
GL.Color (Float (1.0), 0.0, 0.0, 1.0); Draw_Line (-1.0, 0.0, 1.0, 0.0);
GL.Color (Float (0.0), 1.0, 0.0, 1.0); Draw_Line ( 0.0, -1.0, 0.0, 1.0);
end Draw_Axes;
------------------------------------------------------------------------
begin -- Display
-- Clear to black (the default)
GL.Clear (GL.GL_COLOR_BUFFER_BIT);
-- Set up the viewing transforms
GL.Matrix_Mode (GL.GL_MODELVIEW);
GL.Load_Identity;
GL.Translate (XPan, YPan, 0.0);
GL.Scale (Scale, Scale, Scale);
GL.Rotate (RotC, 0.0, 0.0, 1.0);
-- Draw simple 2D axes
Draw_Axes;
GL.Flush;
-- Put the code to draw your objects here:
-- Swap the drawing we just did into the display area
Window.Swap (Win);
-- Update the status bar
end Display;
----------------------------------------------------------------------------
----- -----
----- C A L L B A C K S -----
----- -----
----------------------------------------------------------------------------
-- Callback triggered by the Resized event; tell OpenGL that the
-- user has resized the window
procedure Resize_Handler (Height : in Integer;
Width : in Integer) is
begin -- Resize_Handler
-- Set the new view parameters and redraw the scene
Set_View (Width, Height);
Display;
end Resize_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses
procedure Key_Handler (Category : in Events.Key_Category;
Symbol : in Events.Key_Symbol;
Modifiers : in Events.Modifier_Set) is
use type Events.Key_Symbol;
begin -- Key_Handler
case Symbol is
when Escape | Letter_q =>
Finish;
when Events.Keys.Home =>
RotC := 0.0;
Scale := 1.0;
XPan := 0.0;
YPan := 0.0;
Display;
when others =>
null;
end case;
end Key_Handler;
----------------------------------------------------------------------------
-- Mouse button has been pressed
procedure Button_Handler (X : in Integer;
Y : in Integer;
Button : in Window.Button_Enum;
Modifiers : in Events.Modifier_Set) is
use type Window.Button_Enum;
begin -- Button_Handler
-- Record starting position and current rotation/scale
StartX := GL.Double (X);
StartY := GL.Double (Y);
Curr_RotC := RotC;
Curr_Scale := Scale;
Curr_XPan := XPan;
Curr_YPan := YPan;
-- Handle mouse wheel events
if Button = Window.Button_4 then
Scale := Curr_Scale - 0.1;
Display;
elsif Button = Window.Button_5 then
Scale := Curr_Scale + 0.1;
Display;
end if;
end Button_Handler;
----------------------------------------------------------------------------
-- Mouse movement
procedure Drag_Handler (X : in Integer;
Y : in Integer;
Modifiers : in Events.Modifier_Set) is
Y_Prime : Integer := Curr_H - Y;
begin -- Drag_Handler
-- If it's a drag, update the figure parameters
if Modifiers (Events.Mod_Button_1) then
XPan := Curr_XPan + ((GL.Double (X) - StartX) / GL.Double (Curr_W));
YPan := Curr_YPan + ((GL.Double (Y_Prime) - StartY) / GL.Double (Curr_H));
Display;
elsif Modifiers (Events.Mod_Button_2) then
RotC := GL.Double (Integer (Curr_RotC - ((GL.Double (X) - StartX) + (StartY - GL.Double (Y_Prime)))) mod 360);
Display;
elsif Modifiers (Events.Mod_Button_3) then
Scale := Curr_Scale + ((GL.Double (X) - StartX) / GL.Double (Curr_W)) -
((GL.Double (Y_Prime) - StartY) / GL.Double (Curr_H));
Display;
end if;
end Drag_Handler;
----------------------------------------------------------------------------
-- Re-draw the view
procedure Expose_Handler (Top : in Integer;
Left : in Integer;
Height : in Natural;
Width : in Natural) is
begin -- Expose_Handler
Display;
end Expose_Handler;
----------------------------------------------------------------------------
-- Called once per frame; just re-draws the scene
function New_Frame (Frame_Delta : in Duration) return Boolean is
begin -- New_Frame
Display;
return not Terminated;
end New_Frame;
----------------------------------------------------------------------------
----- -----
----- S E T U P -----
----- -----
----------------------------------------------------------------------------
-- Set up the main window and all its fiddly bits
procedure Init is
begin -- Init
-- Create the main window
Window.Create (Win,
Name => "2D Object Viewer",
Width => Win_Start,
Height => Win_Start);
Win.Exposed := Expose_Handler'Unrestricted_Access;
Win.Resize := Resize_Handler'Unrestricted_Access;
Win.Key_Press := Key_Handler'Unrestricted_Access;
Win.Mouse_Down := Button_Handler'Unrestricted_Access;
Win.Mouse_Move := Drag_Handler'Unrestricted_Access;
Set_View (Win_Start, Win_Start);
Display;
-- Create a packing box to stuff everything into
-- Create the OpenGL drawing area
-- Connect the event handlers
-- Put the OpenGL drawing area into the packing box
-- The status bar
-- The quit button
-- Put any one-time OpenGL initialization code here:
end Init;
-------------------------------------------------------------------------------
----- -----
----- M A I N -----
----- -----
-------------------------------------------------------------------------------
-- The main procedure
begin -- Simple_2D
Init;
-- Framerate assumed to be 24Hz
Lumen.Events.Animate.Run (Win, 24,New_Frame'Unrestricted_Access);
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Simple_2D;
|
Use inverted Y coordinate value that we carefully calculated and then ignored
|
Use inverted Y coordinate value that we carefully calculated and then ignored
|
Ada
|
isc
|
darkestkhan/lumen2,darkestkhan/lumen
|
d3ba2c134a00eee701559b006df8541c1ae3ce4e
|
awa/samples/src/atlas-applications.adb
|
awa/samples/src/atlas-applications.adb
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 2011 unknown
-- Written by unknown ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 Util.Log.Loggers;
with Util.Properties;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
-- with Atlas.XXX.Module;
package body Atlas.Applications is
use AWA.Applications;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas");
-- ------------------------------
-- Initialize the application:
-- <ul>
-- <li>Register the servlets and filters.
-- <li>Register the application modules.
-- <li>Define the servlet and filter mappings.
-- </ul>
-- ------------------------------
procedure Initialize (App : in Application_Access) is
Fact : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
begin
App.Self := App;
begin
C.Load_Properties ("atlas.properties");
Util.Log.Loggers.Initialize (Util.Properties.Manager (C));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Fact);
App.Set_Global ("contextPath", CONTEXT_PATH);
end Initialize;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access);
App.Add_Servlet (Name => "files", Server => App.Self.Files'Access);
App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access);
App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access);
App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access);
App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access);
end Initialize_Filters;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
overriding
procedure Initialize_Modules (App : in out Application) is
begin
Log.Info ("Initializing application modules...");
ASF.Applications.Main.Configs.Read_Configuration (App, "web/WEB-INF/web.xml");
Register (App => App.Self.all'Access,
Name => AWA.Users.Module.NAME,
URI => "user",
Module => App.User_Module'Access);
Register (App => App.Self.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => App.Workspace_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Mail.Module.NAME,
URI => "mail",
Module => App.Mail_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => App.Storage_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Blogs.Module.NAME,
URI => "blogs",
Module => App.Blog_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Comments.Module.NAME,
URI => "comments",
Module => App.Comment_Module'Access);
end Initialize_Modules;
end Atlas.Applications;
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 2011 unknown
-- Written by unknown ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 Util.Log.Loggers;
with Util.Properties;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with AWA.Applications.Factory;
-- with Atlas.XXX.Module;
package body Atlas.Applications is
use AWA.Applications;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas");
-- ------------------------------
-- Initialize the application:
-- <ul>
-- <li>Register the servlets and filters.
-- <li>Register the application modules.
-- <li>Define the servlet and filter mappings.
-- </ul>
-- ------------------------------
procedure Initialize (App : in Application_Access) is
Fact : AWA.Applications.Factory.Application_Factory;
C : ASF.Applications.Config;
begin
App.Self := App;
begin
C.Load_Properties ("atlas.properties");
Util.Log.Loggers.Initialize (Util.Properties.Manager (C));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Fact);
App.Set_Global ("contextPath", CONTEXT_PATH);
end Initialize;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets...");
AWA.Applications.Application (App).Initialize_Servlets;
App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access);
App.Add_Servlet (Name => "files", Server => App.Self.Files'Access);
App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access);
App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access);
App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access);
App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access);
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters...");
AWA.Applications.Application (App).Initialize_Filters;
App.Add_Filter (Name => "dump", Filter => App.Dump'Access);
App.Add_Filter (Name => "measures", Filter => App.Measures'Access);
App.Add_Filter (Name => "service", Filter => App.Service_Filter'Access);
end Initialize_Filters;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
overriding
procedure Initialize_Modules (App : in out Application) is
begin
Log.Info ("Initializing application modules...");
ASF.Applications.Main.Configs.Read_Configuration (App, "web/WEB-INF/web.xml");
Register (App => App.Self.all'Access,
Name => AWA.Users.Module.NAME,
URI => "user",
Module => App.User_Module'Access);
Register (App => App.Self.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => App.Workspace_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Mail.Module.NAME,
URI => "mail",
Module => App.Mail_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => App.Storage_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Blogs.Module.NAME,
URI => "blogs",
Module => App.Blog_Module'Access);
Register (App => App.Self.all'Access,
Name => AWA.Comments.Module.NAME,
URI => "comments",
Module => App.Comment_Module'Access);
end Initialize_Modules;
end Atlas.Applications;
|
Fix initialization of Atlas
|
Fix initialization of Atlas
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e651b2741f226dcf55a5b06ea5230d5d5b148817
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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.Blogs.Models;
with Security.Permissions;
-- == Integration ==
-- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
private
type Blog_Module is new AWA.Modules.Module with null record;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 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 ASF.Applications;
with ADO;
with AWA.Modules;
with AWA.Blogs.Models;
with AWA.Counters.Definition;
with Security.Permissions;
-- == Integration ==
-- The <tt>Blog_Module</tt> manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the <tt>Blog_Module</tt> must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Define the read post counter.
package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
private
type Blog_Module is new AWA.Modules.Module with null record;
end AWA.Blogs.Modules;
|
Define the Read_Counter package for the definition of post read counter
|
Define the Read_Counter package for the definition of post read counter
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3f4644986f247846761ccfcb450c3d30cbf3a4ae
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- 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 AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Strings;
with Ada.Calendar;
with ADO.Sessions;
with ADO.Objects;
with ADO.SQL;
with Util.Log.Loggers;
with Util.Strings.Tokenizers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Setup the resource bundles.
App.Register ("wikiMsg", "wikis");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Admin_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Page_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Page_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_View_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_View_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Version_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Version_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
procedure Copy_Page (Item : in String;
Done : out Boolean);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
procedure Copy_Page (Item : in String;
Done : out Boolean) is
begin
Module.Copy_Page (DB, Wiki, ADO.Identifier'Value (Item));
Done := False;
exception
when Constraint_Error =>
Log.Error ("Invalid configuration wiki page id {0}", Item);
end Copy_Page;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Set_Create_Date (Ada.Calendar.Clock);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Util.Strings.Tokenizers.Iterate_Tokens (Content => Module.Get_Config (PARAM_WIKI_COPY_LIST),
Pattern => ",",
Process => Copy_Page'Access,
Going => Ada.Strings.Forward);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the update wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- Load the wiki page and its content.
-- ------------------------------
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Id);
Page.Load (DB, Id, Found);
Tags.Load_Tags (DB, Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- Load the wiki page and its content from the wiki space Id and the page name.
-- ------------------------------
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
Query : ADO.SQL.Query;
begin
Query.Bind_Param (1, Wiki);
Query.Bind_Param (2, Name);
Query.Set_Filter ("o.wiki_id = ? AND o.name = ?");
Page.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Page.Get_Id);
Tags.Load_Tags (DB, Page.Get_Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- Create a new wiki content for the wiki page.
-- ------------------------------
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
begin
-- Check that the user has the update wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Content;
-- ------------------------------
-- Copy the wiki page with its last version to the wiki space.
-- ------------------------------
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier) is
Page : AWA.Wikis.Models.Wiki_Page_Ref;
Found : Boolean;
begin
Page.Load (DB, Page_Id, Found);
if not Found then
Log.Warn ("Wiki page copy is abandoned: page {0} was not found",
ADO.Identifier'Image (Page_Id));
return;
end if;
Module.Copy_Page (DB, Wiki, Page);
end Copy_Page;
-- ------------------------------
-- Copy the wiki page with its last version to the wiki space.
-- ------------------------------
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is
New_Content : AWA.Wikis.Models.Wiki_Content_Ref;
New_Page : AWA.Wikis.Models.Wiki_Page_Ref;
begin
New_Page.Set_Wiki (Wiki);
New_Page.Set_Title (String '(Page.Get_Title));
New_Page.Set_Name (String '(Page.Get_Name));
New_Page.Set_Is_Public (Wiki.Get_Is_Public);
New_Page.Set_Last_Version (0);
New_Content.Set_Content (String '(Page.Get_Content.Get_Content));
Module.Save_Wiki_Content (DB, New_Page, New_Content);
end Copy_Page;
-- ------------------------------
-- Save a new wiki content for the wiki page.
-- ------------------------------
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
Model.Save_Wiki_Content (DB, Page, Content);
Ctx.Commit;
end Save_Wiki_Content;
-- ------------------------------
-- Save a new wiki content for the wiki page.
-- ------------------------------
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Created : constant Boolean := not Page.Is_Inserted;
begin
Page.Set_Last_Version (Page.Get_Last_Version + 1);
if Created then
Page.Save (DB);
end if;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Set_Page_Version (Page.Get_Last_Version);
Content.Save (DB);
Page.Set_Content (Content);
Page.Save (DB);
if Created then
Wiki_Lifecycle.Notify_Create (Model, Page);
else
Wiki_Lifecycle.Notify_Update (Model, Page);
end if;
end Save_Wiki_Content;
end AWA.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- 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 AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Users.Models;
with AWA.Wikis.Beans;
with AWA.Modules.Beans;
with Ada.Strings;
with Ada.Calendar;
with ADO.Objects;
with ADO.SQL;
with ADO.Statements;
with Util.Log.Loggers;
with Util.Strings.Tokenizers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
package Register is new AWA.Modules.Beans (Module => Wiki_Module,
Module_Access => Wiki_Module_Access);
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
-- Setup the resource bundles.
App.Register ("wikiMsg", "wikis");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Space_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Space_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Admin_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Page_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Page_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_View_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_View_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Wikis.Beans.Wiki_Version_List_Bean",
Handler => AWA.Wikis.Beans.Create_Wiki_Version_List_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
procedure Copy_Page (Item : in String;
Done : out Boolean);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
procedure Copy_Page (Item : in String;
Done : out Boolean) is
begin
Module.Copy_Page (DB, Wiki, ADO.Identifier'Value (Item));
Done := False;
exception
when Constraint_Error =>
Log.Error ("Invalid configuration wiki page id {0}", Item);
end Copy_Page;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Set_Create_Date (Ada.Calendar.Clock);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Util.Strings.Tokenizers.Iterate_Tokens (Content => Module.Get_Config (PARAM_WIKI_COPY_LIST),
Pattern => ",",
Process => Copy_Page'Access,
Going => Ada.Strings.Forward);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
-- ------------------------------
-- Create the wiki page into the wiki space.
-- ------------------------------
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
begin
Log.Info ("Create wiki page {0}", String '(Page.Get_Name));
-- Check that the user has the create wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission,
Entity => Into);
Page.Set_Is_Public (Into.Get_Is_Public);
Page.Set_Wiki (Into);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Page;
-- ------------------------------
-- Save the wiki page.
-- ------------------------------
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the update wiki page permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
Page.Save (DB);
Ctx.Commit;
end Save;
-- ------------------------------
-- Delete the wiki page as well as all its versions.
-- ------------------------------
procedure Delete (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
-- Check that the user has the delete wiki page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Delete_Wiki_Pages.Permission,
Entity => Page);
Ctx.Start;
-- Before deleting the wiki page, delete the version content.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Wikis.Models.WIKI_CONTENT_TABLE);
begin
Stmt.Set_Filter (Filter => "page_id = ?");
Stmt.Add_Param (Value => Page);
Stmt.Execute;
end;
-- Notify the deletion of the wiki page (before the real delete).
Wiki_Lifecycle.Notify_Delete (Model, Page);
Page.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Load the wiki page and its content.
-- ------------------------------
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier) is
DB : ADO.Sessions.Session := Model.Get_Session;
Found : Boolean;
begin
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Id);
Page.Load (DB, Id, Found);
Tags.Load_Tags (DB, Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- Load the wiki page and its content from the wiki space Id and the page name.
-- ------------------------------
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String) is
DB : ADO.Sessions.Session := Model.Get_Session;
Found : Boolean;
Query : ADO.SQL.Query;
begin
Query.Bind_Param (1, Wiki);
Query.Bind_Param (2, Name);
Query.Set_Filter ("o.wiki_id = ? AND o.name = ?");
Page.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
-- Check that the user has the view page permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_View_Wiki_Page.Permission,
Entity => Page.Get_Id);
Tags.Load_Tags (DB, Page.Get_Id);
Content := Page.Get_Content;
if not Content.Is_Null then
Content.Load (DB, Content.Get_Id, Found);
end if;
end Load_Page;
-- ------------------------------
-- Create a new wiki content for the wiki page.
-- ------------------------------
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
begin
-- Check that the user has the update wiki content permission on the given wiki page.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission,
Entity => Page);
Model.Save_Wiki_Content (Page, Content);
end Create_Wiki_Content;
-- ------------------------------
-- Copy the wiki page with its last version to the wiki space.
-- ------------------------------
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier) is
Page : AWA.Wikis.Models.Wiki_Page_Ref;
Found : Boolean;
begin
Page.Load (DB, Page_Id, Found);
if not Found then
Log.Warn ("Wiki page copy is abandoned: page {0} was not found",
ADO.Identifier'Image (Page_Id));
return;
end if;
Module.Copy_Page (DB, Wiki, Page);
end Copy_Page;
-- ------------------------------
-- Copy the wiki page with its last version to the wiki space.
-- ------------------------------
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is
New_Content : AWA.Wikis.Models.Wiki_Content_Ref;
New_Page : AWA.Wikis.Models.Wiki_Page_Ref;
begin
New_Page.Set_Wiki (Wiki);
New_Page.Set_Title (String '(Page.Get_Title));
New_Page.Set_Name (String '(Page.Get_Name));
New_Page.Set_Is_Public (Wiki.Get_Is_Public);
New_Page.Set_Last_Version (0);
New_Content.Set_Content (String '(Page.Get_Content.Get_Content));
Module.Save_Wiki_Content (DB, New_Page, New_Content);
end Copy_Page;
-- ------------------------------
-- Save a new wiki content for the wiki page.
-- ------------------------------
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
Model.Save_Wiki_Content (DB, Page, Content);
Ctx.Commit;
end Save_Wiki_Content;
-- ------------------------------
-- Save a new wiki content for the wiki page.
-- ------------------------------
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Created : constant Boolean := not Page.Is_Inserted;
begin
Page.Set_Last_Version (Page.Get_Last_Version + 1);
if Created then
Page.Save (DB);
end if;
Content.Set_Page (Page);
Content.Set_Create_Date (Ada.Calendar.Clock);
Content.Set_Author (User);
Content.Set_Page_Version (Page.Get_Last_Version);
Content.Save (DB);
Page.Set_Content (Content);
Page.Save (DB);
if Created then
Wiki_Lifecycle.Notify_Create (Model, Page);
else
Wiki_Lifecycle.Notify_Update (Model, Page);
end if;
end Save_Wiki_Content;
end AWA.Wikis.Modules;
|
Implement the Delete procedure to delete the wiki page and all its versions
|
Implement the Delete procedure to delete the wiki page and all its versions
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d343e37fb2163517aad5efa83585f3dc7e6bb607
|
samples/beans/users.adb
|
samples/beans/users.adb
|
-----------------------------------------------------------------------
-- users - Gives access to the OpenID principal through an Ada bean
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
with ASF.Contexts.Flash;
with ASF.Sessions;
with ASF.Principals;
with ASF.Cookies;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Factory;
with GNAT.MD5;
with Security.Openid;
with Security.Filters;
with Util.Strings.Transforms;
package body Users is
use Ada.Strings.Unbounded;
use Security.Openid;
use type ASF.Principals.Principal_Access;
use type ASF.Contexts.Faces.Faces_Context_Access;
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Gravatar_Link (Email : in String) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
return "http://www.gravatar.com/avatar/" & C;
end Get_Gravatar_Link;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
function Get_Value (From : in User_Info;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if F /= null then
S := F.Get_Session;
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
end if;
end if;
if Name = "authenticated" then
return Util.Beans.Objects.To_Object (U /= null);
end if;
if U = null then
return Util.Beans.Objects.Null_Object;
end if;
if Name = "email" then
return Util.Beans.Objects.To_Object (U.Get_Email);
end if;
if Name = "language" then
return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication));
end if;
if Name = "first_name" then
return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication));
end if;
if Name = "last_name" then
return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication));
end if;
if Name = "full_name" then
return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication));
end if;
if Name = "id" then
return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication));
end if;
if Name = "country" then
return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication));
end if;
if Name = "sessionId" then
return Util.Beans.Objects.To_Object (S.Get_Id);
end if;
if Name = "gravatar" then
return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email));
end if;
return Util.Beans.Objects.To_Object (U.Get_Name);
end Get_Value;
-- ------------------------------
-- Helper to send a remove cookie in the current response
-- ------------------------------
procedure Remove_Cookie (Name : in String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Remove_Cookie;
-- ------------------------------
-- Logout by dropping the user session.
-- ------------------------------
procedure Logout (From : in out User_Info;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session := F.Get_Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
S.Invalidate;
end if;
if U /= null then
F.Get_Flash.Set_Keep_Messages (True);
ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message",
Get_Full_Name (U.Get_Authentication));
end if;
Remove_Cookie (Security.Filters.SID_COOKIE);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success");
end Logout;
package Logout_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info,
Method => Logout,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Logout_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in User_Info)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
end Users;
|
-----------------------------------------------------------------------
-- users - Gives access to the OpenID principal through an Ada bean
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
with ASF.Contexts.Flash;
with ASF.Sessions;
with ASF.Principals;
with ASF.Cookies;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Factory;
with GNAT.MD5;
with Security.Openid;
with ASF.Security.Filters;
with Util.Strings.Transforms;
package body Users is
use Ada.Strings.Unbounded;
use Security.Openid;
use type ASF.Principals.Principal_Access;
use type ASF.Contexts.Faces.Faces_Context_Access;
-- ------------------------------
-- Given an Email address, return the Gravatar link to the user image.
-- (See http://en.gravatar.com/site/implement/hash/ and
-- http://en.gravatar.com/site/implement/images/)
-- ------------------------------
function Get_Gravatar_Link (Email : in String) return String is
E : constant String := Util.Strings.Transforms.To_Lower_Case (Email);
C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E);
begin
return "http://www.gravatar.com/avatar/" & C;
end Get_Gravatar_Link;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
function Get_Value (From : in User_Info;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if F /= null then
S := F.Get_Session;
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
end if;
end if;
if Name = "authenticated" then
return Util.Beans.Objects.To_Object (U /= null);
end if;
if U = null then
return Util.Beans.Objects.Null_Object;
end if;
if Name = "email" then
return Util.Beans.Objects.To_Object (U.Get_Email);
end if;
if Name = "language" then
return Util.Beans.Objects.To_Object (Get_Language (U.Get_Authentication));
end if;
if Name = "first_name" then
return Util.Beans.Objects.To_Object (Get_First_Name (U.Get_Authentication));
end if;
if Name = "last_name" then
return Util.Beans.Objects.To_Object (Get_Last_Name (U.Get_Authentication));
end if;
if Name = "full_name" then
return Util.Beans.Objects.To_Object (Get_Full_Name (U.Get_Authentication));
end if;
if Name = "id" then
return Util.Beans.Objects.To_Object (Get_Claimed_Id (U.Get_Authentication));
end if;
if Name = "country" then
return Util.Beans.Objects.To_Object (Get_Country (U.Get_Authentication));
end if;
if Name = "sessionId" then
return Util.Beans.Objects.To_Object (S.Get_Id);
end if;
if Name = "gravatar" then
return Util.Beans.Objects.To_Object (Get_Gravatar_Link (U.Get_Email));
end if;
return Util.Beans.Objects.To_Object (U.Get_Name);
end Get_Value;
-- ------------------------------
-- Helper to send a remove cookie in the current response
-- ------------------------------
procedure Remove_Cookie (Name : in String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, "");
begin
ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path);
ASF.Cookies.Set_Max_Age (C, 0);
Ctx.Get_Response.Add_Cookie (Cookie => C);
end Remove_Cookie;
-- ------------------------------
-- Logout by dropping the user session.
-- ------------------------------
procedure Logout (From : in out User_Info;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (From);
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
S : ASF.Sessions.Session := F.Get_Session;
P : ASF.Principals.Principal_Access := null;
U : Security.Openid.Principal_Access := null;
begin
if S.Is_Valid then
P := S.Get_Principal;
if P /= null then
U := Security.Openid.Principal'Class (P.all)'Access;
end if;
S.Invalidate;
end if;
if U /= null then
F.Get_Flash.Set_Keep_Messages (True);
ASF.Applications.Messages.Factory.Add_Message (F.all, "samples.openid_logout_message",
Get_Full_Name (U.Get_Authentication));
end if;
Remove_Cookie (ASF.Security.Filters.SID_COOKIE);
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("logout_success");
end Logout;
package Logout_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => User_Info,
Method => Logout,
Name => "logout");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Logout_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in User_Info)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
end Users;
|
Fix compilation after Ada Security integration
|
Fix compilation after Ada Security integration
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
95972dac382aa591c68a3e3820860510313f5a2e
|
awa/plugins/awa-wikis/src/awa-wikis-beans.adb
|
awa/plugins/awa-wikis/src/awa-wikis-beans.adb
|
-----------------------------------------------------------------------
-- 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 ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services;
with AWA.Services.Contexts;
package body AWA.Wikis.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki space.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Wiki_Space (Bean);
end Save;
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Space_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
elsif Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki page.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
if Bean.Is_Inserted then
Bean.Service.Save (Bean);
else
Bean.Service.Create_Wiki_Page (Bean.Wiki_Space, Bean);
end if;
end Save;
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Page_Bean_Access := new Wiki_Page_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Page_Bean;
-- ------------------------------
-- Load the list of wikis.
-- ------------------------------
procedure Load_Wikis (List : in Wiki_Admin_Bean) is
use AWA.Wikis.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Wikis.Models.Query_Wiki_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "table",
Table => AWA.Wikis.Models.WIKI_SPACE_TABLE,
Session => Session);
AWA.Wikis.Models.List (List.Wiki_List_Bean.all, Session, Query);
List.Flags (INIT_WIKI_LIST) := True;
end Load_Wikis;
-- ------------------------------
-- Get the wiki space identifier.
-- ------------------------------
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier is
use type ADO.Identifier;
begin
if List.Wiki_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_WIKI_LIST) then
Load_Wikis (List);
end if;
if not List.Wiki_List.List.Is_Empty then
return List.Wiki_List.List.Element (0).Id;
end if;
end if;
return List.Wiki_Id;
end Get_Wiki_Id;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "wikis" then
if not List.Init_Flags (INIT_WIKI_LIST) then
Load_Wikis (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Wiki_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
use type ADO.Identifier;
Id : constant ADO.Identifier := List.Get_Wiki_Id;
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end;
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 Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Wiki_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
-- ------------------------------
-- 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 is
Object : constant Wiki_Admin_Bean_Access := new Wiki_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Wiki_List_Bean := Object.Wiki_List'Access;
return Object.all'Access;
end Create_Wiki_Admin_Bean;
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 ADO.Utils;
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services;
with AWA.Services.Contexts;
package body AWA.Wikis.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki space.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
if Bean.Is_Inserted then
Bean.Service.Save_Wiki_Space (Bean);
else
Bean.Service.Create_Wiki_Space (Bean);
end if;
end Save;
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Space_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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) is
begin
if Name = "name" then
From.Set_Name (Util.Beans.Objects.To_String (Value));
elsif Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the wiki page.
-- ------------------------------
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
if Bean.Is_Inserted then
Bean.Service.Save (Bean);
else
Bean.Service.Create_Wiki_Page (Bean.Wiki_Space, Bean);
end if;
end Save;
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Delete;
-- ------------------------------
-- 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 is
Object : constant Wiki_Page_Bean_Access := new Wiki_Page_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Wiki_Page_Bean;
-- ------------------------------
-- Load the list of wikis.
-- ------------------------------
procedure Load_Wikis (List : in Wiki_Admin_Bean) is
use AWA.Wikis.Models;
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := List.Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Wikis.Models.Query_Wiki_List);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "table",
Table => AWA.Wikis.Models.WIKI_SPACE_TABLE,
Session => Session);
AWA.Wikis.Models.List (List.Wiki_List_Bean.all, Session, Query);
List.Flags (INIT_WIKI_LIST) := True;
end Load_Wikis;
-- ------------------------------
-- Get the wiki space identifier.
-- ------------------------------
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier is
use type ADO.Identifier;
begin
if List.Wiki_Id = ADO.NO_IDENTIFIER then
if not List.Flags (INIT_WIKI_LIST) then
Load_Wikis (List);
end if;
if not List.Wiki_List.List.Is_Empty then
return List.Wiki_List.List.Element (0).Id;
end if;
end if;
return List.Wiki_Id;
end Get_Wiki_Id;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "wikis" then
if not List.Init_Flags (INIT_WIKI_LIST) then
Load_Wikis (List);
end if;
return Util.Beans.Objects.To_Object (Value => List.Wiki_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "id" then
declare
use type ADO.Identifier;
Id : constant ADO.Identifier := List.Get_Wiki_Id;
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end;
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 Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Wiki_Id := ADO.Utils.To_Identifier (Value);
end if;
end Set_Value;
-- ------------------------------
-- 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 is
Object : constant Wiki_Admin_Bean_Access := new Wiki_Admin_Bean;
begin
Object.Module := Module;
Object.Flags := Object.Init_Flags'Access;
Object.Wiki_List_Bean := Object.Wiki_List'Access;
return Object.all'Access;
end Create_Wiki_Admin_Bean;
end AWA.Wikis.Beans;
|
Implement the Save procedure to create or update the wiki space
|
Implement the Save procedure to create or update the wiki space
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
c8d743b0c2b56f7e70ad0fe3001b66aeab5ef538
|
src/security-openid.ads
|
src/security-openid.ads
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- There are basically two steps that an application must implement:
--
-- * Discovery to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * Verify to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the
-- OpenID return callback CB.
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
-- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication
-- URL for the association.
-- * The application should redirected the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
--
-- == Discovery: creating the authentication URL ==
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenId manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>.
--
-- Mgr : Openid.Manager;
-- OP : Openid.End_Point;
-- Assoc : constant Association_Access := new Association;
--
-- The
--
-- Server.Initialize (Mgr);
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- == Verify: acknowledge the authentication in the callback URL ==
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Mgr : Openid.Manager;
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Auth : Openid.Authentication;
-- Params : Auth_Params;
--
-- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Server.Initialize (Mgr);
-- Mgr.Verify (Assoc.all, Params, Auth);
-- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure.
--
--
--
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- 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);
-- 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);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
-----------------------------------------------------------------------
-- security-openid -- Open ID 2.0 Support
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == OpenID ==
-- The <b>Security.Openid</b> package implements an authentication framework based
-- on OpenID 2.0.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- There are basically two steps that an application must implement:
--
-- * Discovery to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * Verify to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the
-- OpenID return callback CB.
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
-- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication
-- URL for the association.
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
--
-- == Discovery: creating the authentication URL ==
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenId manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>.
--
-- Mgr : Openid.Manager;
-- OP : Openid.End_Point;
-- Assoc : constant Association_Access := new Association;
--
-- The
--
-- Server.Initialize (Mgr);
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- == Verify: acknowledge the authentication in the callback URL ==
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Mgr : Openid.Manager;
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Auth : Openid.Authentication;
-- Params : Auth_Params;
--
-- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Server.Initialize (Mgr);
-- Mgr.Verify (Assoc.all, Params, Auth);
-- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure.
--
--
--
package Security.Openid is
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- OpenID provider
-- ------------------------------
-- The <b>End_Point</b> represents the OpenID provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The OpenID association contains the shared secret between the relying party
-- and the OpenID provider. The association can be cached and reused to authenticate
-- different users using the same OpenID provider. The association also has an
-- expiration date.
type Association is private;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- OpenID provider
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- OpenID Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is tagged limited private;
-- Initialize the OpenID realm.
procedure Initialize (Realm : in out Manager;
Name : in String;
Return_To : in String);
-- 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);
-- 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);
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
procedure Discover_XRDS (Realm : in out Manager;
URI : in String;
Result : out End_Point);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
use Ada.Strings.Unbounded;
type Association is record
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager is new Ada.Finalization.Limited_Controlled with record
Realm : Unbounded_String;
Return_To : Unbounded_String;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
end Security.Openid;
|
Fix typo in comment
|
Fix typo in comment
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
6e0817586b47b983c16e4d0d903040178c30961c
|
src/natools-s_expressions-generic_caches.adb
|
src/natools-s_expressions-generic_caches.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Generic_Caches is
--------------------
-- Tree Interface --
--------------------
procedure Append
(Exp : in out Tree;
Kind : in Node_Kind;
Data : in Atom_Access := null)
is
N : Node_Access;
begin
case Kind is
when Atom_Node =>
N := new Node'(Kind => Atom_Node,
Parent | Next => null, Data => Data);
when List_Node =>
N := new Node'(Kind => List_Node, Parent | Next | Child => null);
end case;
if Exp.Root = null then
pragma Assert (Exp.Last = null);
Exp.Root := N;
else
pragma Assert (Exp.Last /= null);
if Exp.Opening then
pragma Assert (Exp.Last.Kind = List_Node);
pragma Assert (Exp.Last.Child = null);
Exp.Last.Child := N;
N.Parent := Exp.Last;
else
pragma Assert (Exp.Last.Next = null);
Exp.Last.Next := N;
N.Parent := Exp.Last.Parent;
end if;
end if;
Exp.Last := N;
Exp.Opening := Kind = List_Node;
end Append;
procedure Close_List (Exp : in out Tree) is
begin
if Exp.Opening then
Exp.Opening := False;
elsif Exp.Last /= null and then Exp.Last.Parent /= null then
Exp.Last := Exp.Last.Parent;
end if;
end Close_List;
function Create_Tree return Tree is
begin
return Tree'(Ada.Finalization.Limited_Controlled
with Root | Last => null, Opening => False);
end Create_Tree;
function Duplicate (Source : Tree) return Tree is
function Dup_List (First, Parent : Node_Access) return Node_Access;
function Dup_Node (N : not null Node_Access; Parent : Node_Access)
return Node_Access;
New_Last : Node_Access := null;
function Dup_List (First, Parent : Node_Access) return Node_Access is
Source : Node_Access := First;
Result, Target : Node_Access;
begin
if First = null then
return null;
end if;
Result := Dup_Node (First, Parent);
Target := Result;
loop
Source := Source.Next;
exit when Source = null;
Target.Next := Dup_Node (Source, Parent);
Target := Target.Next;
end loop;
return Result;
end Dup_List;
function Dup_Node (N : not null Node_Access; Parent : Node_Access)
return Node_Access
is
Result : Node_Access;
begin
case N.Kind is
when Atom_Node =>
Result := new Node'(Kind => Atom_Node,
Parent => Parent,
Next => null,
Data => new Atom'(N.Data.all));
when List_Node =>
Result := new Node'(Kind => List_Node,
Parent => Parent,
Next => null,
Child => null);
Result.Child := Dup_List (N.Child, Result);
end case;
if N = Source.Last then
New_Last := Result;
end if;
return Result;
end Dup_Node;
begin
return Result : Tree do
Result.Root := Dup_List (Source.Root, null);
pragma Assert ((New_Last = null) = (Source.Last = null));
Result.Last := New_Last;
Result.Opening := Source.Opening;
end return;
end Duplicate;
overriding procedure Finalize (Object : in out Tree) is
procedure List_Free (First : in out Node_Access);
procedure List_Free (First : in out Node_Access) is
Next : Node_Access := First;
Cur : Node_Access;
begin
while Next /= null loop
Cur := Next;
case Cur.Kind is
when Atom_Node =>
Unchecked_Free (Cur.Data);
when List_Node =>
List_Free (Cur.Child);
end case;
Next := Cur.Next;
Unchecked_Free (Cur);
end loop;
First := null;
end List_Free;
begin
List_Free (Object.Root);
Object.Last := null;
Object.Opening := False;
end Finalize;
-----------------------
-- Writing Interface --
-----------------------
function Duplicate (Cache : Reference) return Reference is
function Dup_Tree return Tree;
function Dup_Tree return Tree is
begin
return Duplicate (Cache.Exp.Query.Data.all);
end Dup_Tree;
begin
return Reference'(Exp => Trees.Create (Dup_Tree'Access));
end Duplicate;
-----------------------
-- Printer Interface --
-----------------------
overriding procedure Open_List (Output : in out Reference) is
begin
if Output.Exp.Is_Empty then
Output.Exp.Replace (Create_Tree'Access);
end if;
Output.Exp.Update.Data.Append (List_Node);
end Open_List;
overriding procedure Append_Atom
(Output : in out Reference; Data : in Atom) is
begin
if Output.Exp.Is_Empty then
Output.Exp.Replace (Create_Tree'Access);
end if;
Output.Exp.Update.Data.Append (Atom_Node, new Atom'(Data));
end Append_Atom;
overriding procedure Close_List (Output : in out Reference) is
begin
if not Output.Exp.Is_Empty then
Output.Exp.Update.Data.Close_List;
end if;
end Close_List;
-------------------------
-- Reading Subprograms --
-------------------------
function First (Cache : Reference'Class) return Cursor is
N : Node_Access;
begin
if Cache.Exp.Is_Empty then
return Cursor'(others => <>);
else
N := Cache.Exp.Query.Data.Root;
pragma Assert (N /= null);
return Cursor'(Exp => Cache.Exp,
Position => N,
Opening => N.Kind = List_Node,
Stack => <>,
Locked => False);
end if;
end First;
--------------------------
-- Descriptor Interface --
--------------------------
overriding function Current_Event (Object : in Cursor)
return Events.Event is
begin
if Object.Position = null or Object.Locked then
return Events.End_Of_Input;
end if;
case Object.Position.Kind is
when Atom_Node =>
return Events.Add_Atom;
when List_Node =>
if Object.Opening then
return Events.Open_List;
else
return Events.Close_List;
end if;
end case;
end Current_Event;
overriding function Current_Atom (Object : in Cursor) return Atom is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node
or else Object.Locked
then
raise Program_Error;
end if;
return Object.Position.Data.all;
end Current_Atom;
overriding function Current_Level (Object : in Cursor) return Natural is
begin
if Object.Locked then
return 0;
else
return Absolute_Level (Object)
- Lockable.Current_Level (Object.Stack);
end if;
end Current_Level;
overriding procedure Query_Atom
(Object : in Cursor;
Process : not null access procedure (Data : in Atom)) is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node
or else Object.Locked
then
raise Program_Error;
end if;
Process.all (Object.Position.Data.all);
end Query_Atom;
overriding procedure Read_Atom
(Object : in Cursor;
Data : out Atom;
Length : out Count)
is
Transferred : Count;
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node
or else Object.Locked
then
raise Program_Error;
end if;
Length := Object.Position.Data'Length;
Transferred := Count'Min (Data'Length, Length);
Data (Data'First .. Data'First + Transferred - 1)
:= Object.Position.Data (Object.Position.Data'First
.. Object.Position.Data'First + Transferred - 1);
end Read_Atom;
overriding procedure Next
(Object : in out Cursor;
Event : out Events.Event) is
begin
if Object.Position = null or Object.Locked then
Event := Events.End_Of_Input;
return;
end if;
if Object.Opening then
pragma Assert (Object.Position.Kind = List_Node);
if Object.Position.Child = null then
Object.Opening := False;
else
pragma Assert (Object.Position.Child.Parent = Object.Position);
Object.Position := Object.Position.Child;
Object.Opening := Object.Position.Kind = List_Node;
end if;
elsif Object.Position.Next /= null then
pragma Assert (Object.Position.Next.Parent = Object.Position.Parent);
Object.Position := Object.Position.Next;
Object.Opening := Object.Position.Kind = List_Node;
elsif Object.Position.Parent /= null then
pragma Assert (Object.Position.Parent.Kind = List_Node);
Object.Position := Object.Position.Parent;
Object.Opening := False;
else
Object.Position := null;
end if;
Event := Object.Current_Event;
if Event = Events.Close_List
and then Object.Absolute_Level < Lockable.Current_Level (Object.Stack)
then
Event := Events.End_Of_Input;
Object.Locked := True;
end if;
end Next;
-----------------------------------
-- Lockable.Descriptor Interface --
-----------------------------------
function Absolute_Level (Object : Cursor) return Natural is
Result : Natural := 0;
N : Node_Access := Object.Position;
begin
if Object.Position /= null
and then Object.Position.Kind = List_Node
and then Object.Opening
then
Result := Result + 1;
end if;
while N /= null loop
Result := Result + 1;
N := N.Parent;
end loop;
return Natural'Max (Result, 1) - 1;
end Absolute_Level;
overriding procedure Lock
(Object : in out Cursor;
State : out Lockable.Lock_State) is
begin
Lockable.Push_Level (Object.Stack, Object.Absolute_Level, State);
end Lock;
overriding procedure Unlock
(Object : in out Cursor;
State : in out Lockable.Lock_State;
Finish : in Boolean := True)
is
Previous_Level : constant Natural
:= Lockable.Current_Level (Object.Stack);
begin
Lockable.Pop_Level (Object.Stack, State);
State := Lockable.Null_State;
Object.Locked := False;
if Finish then
declare
Event : Events.Event := Object.Current_Event;
begin
loop
case Event is
when Events.Add_Atom | Events.Open_List =>
null;
when Events.Close_List =>
exit when Object.Absolute_Level < Previous_Level;
when Events.Error | Events.End_Of_Input =>
exit;
end case;
Object.Next (Event);
end loop;
end;
end if;
Object.Locked
:= Object.Absolute_Level < Lockable.Current_Level (Object.Stack);
end Unlock;
end Natools.S_Expressions.Generic_Caches;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.S_Expressions.Generic_Caches is
--------------------
-- Tree Interface --
--------------------
procedure Append
(Exp : in out Tree;
Kind : in Node_Kind;
Data : in Atom_Access := null)
is
N : Node_Access;
begin
case Kind is
when Atom_Node =>
N := new Node'(Kind => Atom_Node,
Parent | Next => null, Data => Data);
when List_Node =>
N := new Node'(Kind => List_Node, Parent | Next | Child => null);
end case;
if Exp.Root = null then
pragma Assert (Exp.Last = null);
Exp.Root := N;
else
pragma Assert (Exp.Last /= null);
if Exp.Opening then
pragma Assert (Exp.Last.Kind = List_Node);
pragma Assert (Exp.Last.Child = null);
Exp.Last.Child := N;
N.Parent := Exp.Last;
else
pragma Assert (Exp.Last.Next = null);
Exp.Last.Next := N;
N.Parent := Exp.Last.Parent;
end if;
end if;
Exp.Last := N;
Exp.Opening := Kind = List_Node;
end Append;
procedure Close_List (Exp : in out Tree) is
begin
if Exp.Opening then
Exp.Opening := False;
elsif Exp.Last /= null and then Exp.Last.Parent /= null then
Exp.Last := Exp.Last.Parent;
end if;
end Close_List;
function Create_Tree return Tree is
begin
return Tree'(Ada.Finalization.Limited_Controlled
with Root | Last => null, Opening => False);
end Create_Tree;
function Duplicate (Source : Tree) return Tree is
function Dup_List (First, Parent : Node_Access) return Node_Access;
function Dup_Node (N : not null Node_Access; Parent : Node_Access)
return Node_Access;
New_Last : Node_Access := null;
function Dup_List (First, Parent : Node_Access) return Node_Access is
Source : Node_Access := First;
Result, Target : Node_Access;
begin
if First = null then
return null;
end if;
Result := Dup_Node (First, Parent);
Target := Result;
loop
Source := Source.Next;
exit when Source = null;
Target.Next := Dup_Node (Source, Parent);
Target := Target.Next;
end loop;
return Result;
end Dup_List;
function Dup_Node (N : not null Node_Access; Parent : Node_Access)
return Node_Access
is
Result : Node_Access;
begin
case N.Kind is
when Atom_Node =>
Result := new Node'(Kind => Atom_Node,
Parent => Parent,
Next => null,
Data => new Atom'(N.Data.all));
when List_Node =>
Result := new Node'(Kind => List_Node,
Parent => Parent,
Next => null,
Child => null);
Result.Child := Dup_List (N.Child, Result);
end case;
if N = Source.Last then
New_Last := Result;
end if;
return Result;
end Dup_Node;
begin
return Result : Tree do
Result.Root := Dup_List (Source.Root, null);
pragma Assert ((New_Last = null) = (Source.Last = null));
Result.Last := New_Last;
Result.Opening := Source.Opening;
end return;
end Duplicate;
overriding procedure Finalize (Object : in out Tree) is
procedure List_Free (First : in out Node_Access);
procedure List_Free (First : in out Node_Access) is
Next : Node_Access := First;
Cur : Node_Access;
begin
while Next /= null loop
Cur := Next;
case Cur.Kind is
when Atom_Node =>
Unchecked_Free (Cur.Data);
when List_Node =>
List_Free (Cur.Child);
end case;
Next := Cur.Next;
Unchecked_Free (Cur);
end loop;
First := null;
end List_Free;
begin
List_Free (Object.Root);
Object.Last := null;
Object.Opening := False;
end Finalize;
-----------------------
-- Writing Interface --
-----------------------
function Duplicate (Cache : Reference) return Reference is
function Dup_Tree return Tree;
function Dup_Tree return Tree is
begin
return Duplicate (Cache.Exp.Query.Data.all);
end Dup_Tree;
begin
return Reference'(Exp => Trees.Create (Dup_Tree'Access));
end Duplicate;
-----------------------
-- Printer Interface --
-----------------------
overriding procedure Open_List (Output : in out Reference) is
begin
if Output.Exp.Is_Empty then
Output.Exp.Replace (Create_Tree'Access);
end if;
Output.Exp.Update.Data.Append (List_Node);
end Open_List;
overriding procedure Append_Atom
(Output : in out Reference; Data : in Atom) is
begin
if Output.Exp.Is_Empty then
Output.Exp.Replace (Create_Tree'Access);
end if;
Output.Exp.Update.Data.Append (Atom_Node, new Atom'(Data));
end Append_Atom;
overriding procedure Close_List (Output : in out Reference) is
begin
if not Output.Exp.Is_Empty then
Output.Exp.Update.Data.Close_List;
end if;
end Close_List;
-------------------------
-- Reading Subprograms --
-------------------------
function First (Cache : Reference'Class) return Cursor is
N : Node_Access;
begin
if Cache.Exp.Is_Empty then
return Cursor'(others => <>);
else
N := Cache.Exp.Query.Data.Root;
pragma Assert (N /= null);
return Cursor'(Exp => Cache.Exp,
Position => N,
Opening => N.Kind = List_Node,
Stack => <>,
Locked => False);
end if;
end First;
--------------------------
-- Descriptor Interface --
--------------------------
overriding function Current_Event (Object : in Cursor)
return Events.Event is
begin
if Object.Position = null or Object.Locked then
return Events.End_Of_Input;
end if;
case Object.Position.Kind is
when Atom_Node =>
return Events.Add_Atom;
when List_Node =>
if Object.Opening then
return Events.Open_List;
else
return Events.Close_List;
end if;
end case;
end Current_Event;
overriding function Current_Atom (Object : in Cursor) return Atom is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node
or else Object.Locked
then
raise Program_Error;
end if;
return Object.Position.Data.all;
end Current_Atom;
overriding function Current_Level (Object : in Cursor) return Natural is
begin
if Object.Locked then
return 0;
else
return Absolute_Level (Object)
- Lockable.Current_Level (Object.Stack);
end if;
end Current_Level;
overriding procedure Query_Atom
(Object : in Cursor;
Process : not null access procedure (Data : in Atom)) is
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node
or else Object.Locked
then
raise Program_Error;
end if;
Process.all (Object.Position.Data.all);
end Query_Atom;
overriding procedure Read_Atom
(Object : in Cursor;
Data : out Atom;
Length : out Count)
is
Transferred : Count;
begin
if Object.Position = null or else Object.Position.Kind /= Atom_Node
or else Object.Locked
then
raise Program_Error;
end if;
Length := Object.Position.Data'Length;
Transferred := Count'Min (Data'Length, Length);
Data (Data'First .. Data'First + Transferred - 1)
:= Object.Position.Data (Object.Position.Data'First
.. Object.Position.Data'First + Transferred - 1);
end Read_Atom;
overriding procedure Next
(Object : in out Cursor;
Event : out Events.Event) is
begin
if Object.Position = null or Object.Locked then
Event := Events.End_Of_Input;
return;
end if;
if Object.Opening then
pragma Assert (Object.Position.Kind = List_Node);
if Object.Position.Child = null then
Object.Opening := False;
else
pragma Assert (Object.Position.Child.Parent = Object.Position);
Object.Position := Object.Position.Child;
Object.Opening := Object.Position.Kind = List_Node;
end if;
elsif Object.Position.Next /= null then
pragma Assert (Object.Position.Next.Parent = Object.Position.Parent);
Object.Position := Object.Position.Next;
Object.Opening := Object.Position.Kind = List_Node;
elsif Object.Position.Parent /= null then
pragma Assert (Object.Position.Parent.Kind = List_Node);
Object.Position := Object.Position.Parent;
Object.Opening := False;
else
Object.Position := null;
end if;
Event := Object.Current_Event;
if Event = Events.Close_List
and then Object.Absolute_Level < Lockable.Current_Level (Object.Stack)
then
Event := Events.End_Of_Input;
Object.Locked := True;
end if;
end Next;
-----------------------------------
-- Lockable.Descriptor Interface --
-----------------------------------
function Absolute_Level (Object : Cursor) return Natural is
Result : Natural := 0;
N : Node_Access := Object.Position;
begin
if Object.Position /= null
and then Object.Position.Kind = List_Node
and then Object.Opening
then
Result := Result + 1;
end if;
while N /= null loop
Result := Result + 1;
N := N.Parent;
end loop;
return Natural'Max (Result, 1) - 1;
end Absolute_Level;
overriding procedure Lock
(Object : in out Cursor;
State : out Lockable.Lock_State) is
begin
Lockable.Push_Level (Object.Stack, Object.Absolute_Level, State);
end Lock;
overriding procedure Unlock
(Object : in out Cursor;
State : in out Lockable.Lock_State;
Finish : in Boolean := True)
is
Previous_Level : constant Natural
:= Lockable.Current_Level (Object.Stack);
begin
Lockable.Pop_Level (Object.Stack, State);
State := Lockable.Null_State;
Object.Locked := False;
if Finish and Object.Position /= null then
if Object.Position.Kind = List_Node and then Object.Opening then
Object.Opening := False;
end if;
pragma Assert (not Object.Opening);
for I in 1 .. Object.Absolute_Level - Previous_Level + 1 loop
Object.Position := Object.Position.Parent;
end loop;
end if;
Object.Locked
:= Object.Absolute_Level < Lockable.Current_Level (Object.Stack);
end Unlock;
end Natools.S_Expressions.Generic_Caches;
|
use Parent links to unwind levels much faster when unlocking
|
s_expressions-generic_caches: use Parent links to unwind levels much faster when unlocking
|
Ada
|
isc
|
faelys/natools
|
5b0a0d95acf6ba8040ec39a9d219f4ee238004eb
|
tools/druss-commands.adb
|
tools/druss-commands.adb
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- 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 Druss.Commands.Bboxes;
with Druss.Commands.Get;
with Druss.Commands.Status;
with Druss.Commands.Wifi;
package body Druss.Commands is
Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type;
Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type;
Get_Commands : aliased Druss.Commands.Get.Command_Type;
Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type;
procedure Initialize is
begin
Driver.Set_Description ("Druss - The Bbox master controller");
Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF &
"where:" & ASCII.LF &
" -v Verbose execution mode" & ASCII.LF &
" -c config Use the configuration file" &
" (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF &
" -o file The output file to use");
Driver.Add_Command ("help", Help_Command'Access);
Driver.Add_Command ("bbox", Bbox_Commands'Access);
Driver.Add_Command ("get", Get_Commands'Access);
Driver.Add_Command ("wifi", Wifi_Commands'Access);
Driver.Add_Command ("status", Druss.Commands.Status.Wan_Status'Access);
end Initialize;
end Druss.Commands;
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- 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 Druss.Commands.Bboxes;
with Druss.Commands.Get;
with Druss.Commands.Status;
with Druss.Commands.Wifi;
package body Druss.Commands is
Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type;
Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type;
Get_Commands : aliased Druss.Commands.Get.Command_Type;
Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type) is
begin
if Args.Get_Count < Arg_Pos + 1 then
Druss.Commands.Driver.Usage (Args);
end if;
declare
Param : constant String := Args.Get_Argument (Arg_Pos);
Gw : Druss.Gateways.Gateway_Ref;
procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is
begin
Process (Gateway, Param);
end Operation;
begin
if Args.Get_Count = Arg_Pos then
Druss.Gateways.Iterate (Context.Gateways, Operation'Access);
else
for I in Arg_Pos + 1 .. Args.Get_Count loop
Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I));
if not Gw.Is_Null then
Operation (Gw.Value.all);
end if;
end loop;
end if;
end;
end Gateway_Command;
procedure Initialize is
begin
Driver.Set_Description ("Druss - The Bbox master controller");
Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF &
"where:" & ASCII.LF &
" -v Verbose execution mode" & ASCII.LF &
" -c config Use the configuration file" &
" (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF &
" -o file The output file to use");
Driver.Add_Command ("help", Help_Command'Access);
Driver.Add_Command ("bbox", Bbox_Commands'Access);
Driver.Add_Command ("get", Get_Commands'Access);
Driver.Add_Command ("wifi", Wifi_Commands'Access);
Driver.Add_Command ("status", Druss.Commands.Status.Wan_Status'Access);
end Initialize;
end Druss.Commands;
|
Implement the Gateway_Command procedure
|
Implement the Gateway_Command procedure
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
c92a01f6a6f74bccd0c381211ec94f37c1ca700d
|
src/wiki-render-html.adb
|
src/wiki-render-html.adb
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
package ACC renames Ada.Characters.Conversions;
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access) is
begin
Document.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Close_Paragraph;
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Output.Write (Node.Header);
Engine.Add_Line_Break;
Engine.Add_Header (Header => Node.Header,
Level => Node.Level);
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Add_Line_Break;
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Output.Start_Element ("hr");
Engine.Output.End_Element ("hr");
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
Engine.Add_Line_Break;
when Wiki.Nodes.N_INDENT =>
Engine.Indent_Level := Node.Level;
when Wiki.Nodes.N_TEXT =>
if Engine.Empty_Line and Engine.Indent_Level /= 0 then
for I in 1 .. Engine.Indent_Level loop
Engine.Output.Write (' ');
end loop;
end if;
Engine.Output.Write (Node.Text);
Engine.Empty_Line := False;
when Wiki.Nodes.N_QUOTE =>
Engine.Open_Paragraph;
Engine.Output.Write (Node.Quote);
Engine.Empty_Line := False;
when Wiki.Nodes.N_LINK =>
Engine.Add_Link (Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
null;
when Wiki.Nodes.N_BLOCKQUOTE =>
null;
when Wiki.Nodes.N_TAG_START =>
if Node.Children /= null then
if Node.Tag_Start = Wiki.Nodes.DT_TAG then
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
elsif Node.Tag_Start = Wiki.Nodes.DD_TAG then
Engine.Close_Paragraph;
Engine.Empty_Line := True;
Engine.Indent_Level := 4;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
else
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.Nodes.DL_TAG then
Engine.Close_Paragraph;
Engine.New_Line;
end if;
end if;
end if;
end case;
end Render;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
case Level is
when 1 =>
Engine.Output.Write_Wide_Element ("h1", Header);
when 2 =>
Engine.Output.Write_Wide_Element ("h2", Header);
when 3 =>
Engine.Output.Write_Wide_Element ("h3", Header);
when 4 =>
Engine.Output.Write_Wide_Element ("h4", Header);
when 5 =>
Engine.Output.Write_Wide_Element ("h5", Header);
when 6 =>
Engine.Output.Write_Wide_Element ("h6", Header);
when others =>
Engine.Output.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Html_Renderer) is
begin
Document.Writer.Write ("<br />");
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Writer.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Writer.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Writer.Start_Element ("ol");
else
Document.Writer.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Writer.End_Element ("ol");
else
Document.Writer.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Need_Paragraph then
Document.Writer.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Writer.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
Exists : Boolean;
URI : Unbounded_Wide_Wide_String;
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("a");
if Length (Title) > 0 then
Document.Writer.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
Document.Links.Make_Page_Link (Link, URI, Exists);
Document.Writer.Write_Wide_Attribute ("href", URI);
Document.Writer.Write_Wide_Text (Name);
Document.Writer.End_Element ("a");
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
URI : Unbounded_Wide_Wide_String;
Width : Natural;
Height : Natural;
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("img");
if Length (Alt) > 0 then
Document.Writer.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Links.Make_Image_Link (Link, URI, Width, Height);
Document.Writer.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Document.Writer.Write_Attribute ("width", Natural'Image (Width));
end if;
if Height > 0 then
Document.Writer.Write_Attribute ("height", Natural'Image (Height));
end if;
Document.Writer.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("q");
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Writer.Write_Wide_Attribute ("cite", Link);
end if;
Document.Writer.Write_Wide_Text (Quote);
Document.Writer.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(Documents.BOLD => HTML_BOLD'Access,
Documents.ITALIC => HTML_ITALIC'Access,
Documents.CODE => HTML_CODE'Access,
Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access,
Documents.STRIKEOUT => HTML_STRIKEOUT'Access,
Documents.PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Document.Writer.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Document.Writer.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Document.Writer.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Writer.Write (Text);
else
Document.Writer.Start_Element ("pre");
Document.Writer.Write_Wide_Text (Text);
Document.Writer.End_Element ("pre");
end if;
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Attributes);
begin
Document.Html_Level := Document.Html_Level + 1;
if Name = "p" then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
Document.Writer.Start_Element (ACC.To_String (To_Wide_Wide_String (Name)));
while Wiki.Attributes.Has_Element (Iter) loop
Document.Writer.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
end Start_Element;
overriding
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Html_Level := Document.Html_Level - 1;
if Name = "p" then
Document.Has_Paragraph := False;
Document.Need_Paragraph := True;
end if;
Document.Writer.End_Element (ACC.To_String (To_Wide_Wide_String (Name)));
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
package ACC renames Ada.Characters.Conversions;
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access) is
begin
Document.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Close_Paragraph;
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Output.Write (Node.Header);
Engine.Add_Line_Break;
Engine.Add_Header (Header => Node.Header,
Level => Node.Level);
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Add_Line_Break;
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Output.Start_Element ("hr");
Engine.Output.End_Element ("hr");
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
when Wiki.Nodes.N_INDENT =>
Engine.Indent_Level := Node.Level;
when Wiki.Nodes.N_TEXT =>
if Engine.Empty_Line and Engine.Indent_Level /= 0 then
for I in 1 .. Engine.Indent_Level loop
Engine.Output.Write (' ');
end loop;
end if;
Engine.Output.Write (Node.Text);
Engine.Empty_Line := False;
when Wiki.Nodes.N_QUOTE =>
Engine.Open_Paragraph;
Engine.Output.Write (Node.Quote);
Engine.Empty_Line := False;
when Wiki.Nodes.N_LINK =>
Engine.Add_Link (Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
null;
when Wiki.Nodes.N_BLOCKQUOTE =>
null;
when Wiki.Nodes.N_TAG_START =>
if Node.Children /= null then
if Node.Tag_Start = Wiki.Nodes.DT_TAG then
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
elsif Node.Tag_Start = Wiki.Nodes.DD_TAG then
Engine.Close_Paragraph;
Engine.Empty_Line := True;
Engine.Indent_Level := 4;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
else
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.Nodes.DL_TAG then
Engine.Close_Paragraph;
Engine.New_Line;
end if;
end if;
end if;
end case;
end Render;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
case Level is
when 1 =>
Engine.Output.Write_Wide_Element ("h1", Header);
when 2 =>
Engine.Output.Write_Wide_Element ("h2", Header);
when 3 =>
Engine.Output.Write_Wide_Element ("h3", Header);
when 4 =>
Engine.Output.Write_Wide_Element ("h4", Header);
when 5 =>
Engine.Output.Write_Wide_Element ("h5", Header);
when 6 =>
Engine.Output.Write_Wide_Element ("h6", Header);
when others =>
Engine.Output.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Html_Renderer) is
begin
Document.Writer.Write ("<br />");
end Add_Line_Break;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Writer.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Writer.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Writer.Start_Element ("ol");
else
Document.Writer.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Writer.End_Element ("ol");
else
Document.Writer.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Need_Paragraph then
Document.Writer.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Writer.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
Exists : Boolean;
URI : Unbounded_Wide_Wide_String;
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("a");
if Length (Title) > 0 then
Document.Writer.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
Document.Links.Make_Page_Link (Link, URI, Exists);
Document.Writer.Write_Wide_Attribute ("href", URI);
Document.Writer.Write_Wide_Text (Name);
Document.Writer.End_Element ("a");
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
URI : Unbounded_Wide_Wide_String;
Width : Natural;
Height : Natural;
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("img");
if Length (Alt) > 0 then
Document.Writer.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Links.Make_Image_Link (Link, URI, Width, Height);
Document.Writer.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Document.Writer.Write_Attribute ("width", Natural'Image (Width));
end if;
if Height > 0 then
Document.Writer.Write_Attribute ("height", Natural'Image (Height));
end if;
Document.Writer.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("q");
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Writer.Write_Wide_Attribute ("cite", Link);
end if;
Document.Writer.Write_Wide_Text (Quote);
Document.Writer.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(Documents.BOLD => HTML_BOLD'Access,
Documents.ITALIC => HTML_ITALIC'Access,
Documents.CODE => HTML_CODE'Access,
Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access,
Documents.STRIKEOUT => HTML_STRIKEOUT'Access,
Documents.PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
begin
Document.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Document.Writer.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Document.Writer.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Document.Writer.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Writer.Write (Text);
else
Document.Writer.Start_Element ("pre");
Document.Writer.Write_Wide_Text (Text);
Document.Writer.End_Element ("pre");
end if;
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Attributes);
begin
Document.Html_Level := Document.Html_Level + 1;
if Name = "p" then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
Document.Writer.Start_Element (ACC.To_String (To_Wide_Wide_String (Name)));
while Wiki.Attributes.Has_Element (Iter) loop
Document.Writer.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
end Start_Element;
overriding
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Html_Level := Document.Html_Level - 1;
if Name = "p" then
Document.Has_Paragraph := False;
Document.Need_Paragraph := True;
end if;
Document.Writer.End_Element (ACC.To_String (To_Wide_Wide_String (Name)));
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
Remove the Add_Paragraph procedure
|
Remove the Add_Paragraph procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
e81b70ebb2fb16cf711b00f5b50d07bdaa8e6ea6
|
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
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_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_TAG_ATTR : constant String := "tags";
-- ------------------------------
-- 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);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- 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.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- 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;
-- 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;
-- List of posts visible to anybody.
type Post_List_Bean is limited new Util.Beans.Basic.Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_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);
-- 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;
-- 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;
-- 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;
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);
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog 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 Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
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_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_TAG_ATTR : constant String := "tags";
POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments";
-- ------------------------------
-- 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);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- 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.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- 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;
-- 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;
-- List of posts visible to anybody.
type Post_List_Bean is limited new Util.Beans.Basic.Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_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);
-- 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;
-- 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;
-- 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;
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);
end AWA.Blogs.Beans;
|
Define POST_ALLOW_COMMENTS_ATTR constant
|
Define POST_ALLOW_COMMENTS_ATTR constant
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a4a5469d7ae4b134f0475923932cb56c053788f3
|
src/wiki-strings.ads
|
src/wiki-strings.ads
|
-----------------------------------------------------------------------
-- wiki-strings -- Wiki string types and operations
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Characters.Conversions;
with Util.Texts.Builders;
package Wiki.Strings is
pragma Preelaborate;
subtype WChar is Wide_Wide_Character;
subtype WString is Wide_Wide_String;
subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
function To_WChar (C : in Character) return WChar
renames Ada.Characters.Conversions.To_Wide_Wide_Character;
function To_Char (C : in WChar; Substitute : in Character := ' ') return Character
renames Ada.Characters.Conversions.To_Character;
function To_String (S : in WString; Substitute : in Character := ' ') return String
renames Ada.Characters.Conversions.To_String;
function To_UString (S : in WString) return UString
renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String;
function To_WString (S : in UString) return WString
renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String;
Null_UString : UString
renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String;
package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar,
Input => WString,
Chunk_Size => 512);
subtype BString is Wide_Wide_Builders.Builder;
end Wiki.Strings;
|
-----------------------------------------------------------------------
-- wiki-strings -- Wiki string types and operations
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Characters.Conversions;
with Util.Texts.Builders;
package Wiki.Strings is
pragma Preelaborate;
subtype WChar is Wide_Wide_Character;
subtype WString is Wide_Wide_String;
subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
function To_WChar (C : in Character) return WChar
renames Ada.Characters.Conversions.To_Wide_Wide_Character;
function To_Char (C : in WChar; Substitute : in Character := ' ') return Character
renames Ada.Characters.Conversions.To_Character;
function To_String (S : in WString; Substitute : in Character := ' ') return String
renames Ada.Characters.Conversions.To_String;
function To_UString (S : in WString) return UString
renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String;
function To_WString (S : in UString) return WString
renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String;
function To_WString (S : in String) return WString
renames Ada.Characters.Conversions.To_Wide_Wide_String;
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 To_WString function
|
Declare To_WString function
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
2fa739a66dae814ebffc43c0b756f232803138a0
|
src/security-auth.ads
|
src/security-auth.ads
|
-----------------------------------------------------------------------
-- security-auth -- Authentication Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == Auth ==
-- The <b>Security.Auth</b> package implements an authentication framework that is
-- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application
-- to authenticate users using an external authorization server such as Google, Facebook,
-- Google +, Twitter and others.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- See OpenID Connect Standard 1.0
-- http://openid.net/specs/openid-connect-standard-1_0.html
--
-- See Facebook API: The Login Flow for Web (without JavaScript SDK)
-- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
--
-- Despite their subtle differences, all these authentication frameworks share almost
-- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable
-- for all these frameworks.
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The Authentication manager must be declared and configured.
--
-- Mgr : Security.Auth.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the Auth realm and set the authentication return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify",
-- Realm => "openid");
--
-- After this initialization, the authentication manager can be used in the authentication
-- process.
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenID manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Security.Auth.End_Point;
-- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Credential : Security.Auth.Authentication;
-- Params : Auth_Params;
--
-- The auth manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Credential);
-- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success.
--
-- === Principal creation ===
-- After the user is successfully authenticated, a user principal can be created and saved in
-- the session. The user principal can then be used to assign permissions to that user and
-- enforce the application permissions using the security policy manger.
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential);
--
package Security.Auth is
-- Use an authentication server implementing OpenID 2.0.
PROVIDER_OPENID : constant String := "openid";
-- Use the Facebook OAuth 2.0 - draft 12 authentication server.
PROVIDER_FACEBOOK : constant String := "facebook";
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- Auth provider
-- ------------------------------
-- The <b>End_Point</b> represents the authentication provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The association contains the shared secret between the relying party
-- and the authentication provider. The association can be cached and reused to authenticate
-- different users using the same authentication provider. The association also has an
-- expiration date.
type Association is private;
-- Get the provider.
function Get_Provider (Assoc : in Association) return String;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- Authentication result
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- Authentication Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the authentication process.
type Manager is tagged limited private;
-- Initialize the authentication realm.
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the authentication provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned. The discover step may do nothing for
-- authentication providers based on OAuth.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the authentication provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
private
use Ada.Strings.Unbounded;
type Association is record
Provider : Unbounded_String;
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager_Access is access all Manager'Class;
type Manager is new Ada.Finalization.Limited_Controlled with record
Provider : Unbounded_String;
Delegate : Manager_Access;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String);
end Security.Auth;
|
-----------------------------------------------------------------------
-- security-auth -- Authentication Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == Auth ==
-- The <b>Security.Auth</b> package implements an authentication framework that is
-- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application
-- to authenticate users using an external authorization server such as Google, Facebook,
-- Google +, Twitter and others.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- See OpenID Connect Standard 1.0
-- http://openid.net/specs/openid-connect-standard-1_0.html
--
-- See Facebook API: The Login Flow for Web (without JavaScript SDK)
-- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
--
-- Despite their subtle differences, all these authentication frameworks share almost
-- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable
-- for all these frameworks.
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The Authentication manager must be declared and configured.
--
-- Mgr : Security.Auth.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the Auth realm and set the authentication return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify",
-- Realm => "openid");
--
-- After this initialization, the authentication manager can be used in the authentication
-- process.
--
-- @include security-auth-openid.ads
-- @include security-auth-oauth.ads
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenID manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Security.Auth.End_Point;
-- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Credential : Security.Auth.Authentication;
-- Params : Auth_Params;
--
-- The auth manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Credential);
-- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success.
--
-- === Principal creation ===
-- After the user is successfully authenticated, a user principal can be created and saved in
-- the session. The user principal can then be used to assign permissions to that user and
-- enforce the application permissions using the security policy manger.
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential);
--
package Security.Auth is
-- Use an authentication server implementing OpenID 2.0.
PROVIDER_OPENID : constant String := "openid";
-- Use the Facebook OAuth 2.0 - draft 12 authentication server.
PROVIDER_FACEBOOK : constant String := "facebook";
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- Auth provider
-- ------------------------------
-- The <b>End_Point</b> represents the authentication provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The association contains the shared secret between the relying party
-- and the authentication provider. The association can be cached and reused to authenticate
-- different users using the same authentication provider. The association also has an
-- expiration date.
type Association is private;
-- Get the provider.
function Get_Provider (Assoc : in Association) return String;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- Authentication result
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- Authentication Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the authentication process.
type Manager is tagged limited private;
-- Initialize the authentication realm.
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the authentication provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned. The discover step may do nothing for
-- authentication providers based on OAuth.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the authentication provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
private
use Ada.Strings.Unbounded;
type Association is record
Provider : Unbounded_String;
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager_Access is access all Manager'Class;
type Manager is new Ada.Finalization.Limited_Controlled with record
Provider : Unbounded_String;
Delegate : Manager_Access;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String);
end Security.Auth;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
90fdf90bfe6025f3e1beec65a42f4fce40456cd5
|
mat/src/mat-expressions.ads
|
mat/src/mat-expressions.ads
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_CONDITION, N_THREAD);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a new expression node.
function Create (Kindx : in Kind_Type;
Expr : in Expression_Type) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Context : in Context_Type) return Boolean;
private
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when others =>
null;
end case;
end record;
function Is_Selected (Node : in Node_Type;
Context : in Context_Type) return Boolean;
type Expression_Type is tagged record
Node : Node_Type_Access;
end record;
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_CONDITION, N_THREAD);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a new expression node.
function Create (Kindx : in Kind_Type;
Expr : in Expression_Type) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Context : in Context_Type) return Boolean;
private
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when others =>
null;
end case;
end record;
function Is_Selected (Node : in Node_Type;
Context : in Context_Type) return Boolean;
type Expression_Type is tagged record
Node : Node_Type_Access;
end record;
end MAT.Expressions;
|
Define the Create_Or operation
|
Define the Create_Or operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
0df08bd924511f48a36f5d185d87d10730d73196
|
src/os-win32/util-processes-os.ads
|
src/os-win32/util-processes-os.ads
|
-----------------------------------------------------------------------
-- util-processes-os -- Windows specific and low level operations
-- Copyright (C) 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Raw;
with Util.Systems.Os;
with Interfaces.C;
private package Util.Processes.Os is
use Util.Systems.Os;
SHELL : constant String := "";
type Wchar_Ptr is access all Interfaces.C.wchar_array;
type System_Process is new Util.Processes.System_Process with record
Process_Info : aliased Util.Systems.Os.PROCESS_INFORMATION;
Command : Wchar_Ptr := null;
Pos : Interfaces.C.size_t := 0;
end record;
-- Wait for the process to exit.
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration);
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15);
-- Append the argument to the process argument list.
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String);
-- Set the process input, output and error streams to redirect and use specified files.
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean);
-- Deletes the storage held by the system process.
overriding
procedure Finalize (Sys : in out System_Process);
-- Build the output pipe redirection to read the process output.
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
-- Build the input pipe redirection to write the process standard input.
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
private
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- Windows specific and low level operations
-- Copyright (C) 2011, 2012, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Raw;
with Util.Systems.Os;
with Interfaces.C;
private package Util.Processes.Os is
use Util.Systems.Os;
SHELL : constant String := "";
type Wchar_Ptr is access all Interfaces.C.wchar_array;
type System_Process is new Util.Processes.System_Process with record
Process_Info : aliased Util.Systems.Os.PROCESS_INFORMATION;
Command : Wchar_Ptr := null;
Pos : Interfaces.C.size_t := 0;
To_Close : File_Type_Array_Access;
end record;
-- Wait for the process to exit.
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration);
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE);
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15);
-- Append the argument to the process argument list.
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String);
-- Set the process input, output and error streams to redirect and use specified files.
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access);
-- Deletes the storage held by the system process.
overriding
procedure Finalize (Sys : in out System_Process);
-- Build the output pipe redirection to read the process output.
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
-- Build the input pipe redirection to write the process standard input.
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info);
private
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access;
end Util.Processes.Os;
|
Add a To_Close parameter to Set_Streams
|
Add a To_Close parameter to Set_Streams
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
532fdf90d2fc8962afccc4969d8058538cac8a78
|
src/gen-model-packages.adb
|
src/gen-model-packages.adb
|
-----------------------------------------------------------------------
-- gen-model-packages -- Packages holding model, query representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Maps;
with Gen.Utils;
with Gen.Model.Enums;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Gen.Model.Mappings;
with Gen.Model.Beans;
with Util.Strings;
with Util.Strings.Transforms;
with Util.Log.Loggers;
package body Gen.Model.Packages is
use type DOM.Core.Node;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Packages");
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Package_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (From.Pkg_Name);
elsif Name = "package" then
return Util.Beans.Objects.To_Object (From.Base_Name);
elsif Name = "tables" then
return From.Tables_Bean;
elsif Name = "enums" then
return From.Enums_Bean;
elsif Name = "queries" then
return From.Queries_Bean;
elsif Name = "beans" then
return From.Beans_Bean;
elsif Name = "usedTypes" then
return From.Used;
elsif Name = "useCalendarTime" then
return Util.Beans.Objects.To_Object (From.Uses_Calendar_Time);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Register the declaration of the given enum in the model.
-- ------------------------------
procedure Register_Enum (O : in out Model_Definition;
Enum : access Gen.Model.Enums.Enum_Definition'Class) is
Name : constant String := Enum.Get_Name;
begin
Log.Info ("Registering enum {0}", Name);
O.Register_Package (Enum.Pkg_Name, Enum.Package_Def);
if Enum.Package_Def.Enums.Find (Name) /= null then
raise Name_Exist with "Enum '" & Name & "' already defined";
end if;
Enum.Package_Def.Enums.Append (Enum.all'Access);
O.Enums.Append (Enum.all'Access);
Gen.Model.Mappings.Register_Type (To_String (Enum.Name), Enum.all'Access,
Gen.Model.Mappings.T_ENUM);
end Register_Enum;
-- ------------------------------
-- Register the declaration of the given table in the model.
-- ------------------------------
procedure Register_Table (O : in out Model_Definition;
Table : access Gen.Model.Tables.Table_Definition'Class) is
Name : constant String := Table.Get_Name;
begin
Log.Info ("Registering table {0}", Name);
O.Register_Package (Table.Pkg_Name, Table.Package_Def);
if Table.Package_Def.Tables.Find (Name) /= null then
raise Name_Exist with "Table '" & Name & "' already defined";
end if;
Table.Package_Def.Tables.Append (Table.all'Access);
O.Tables.Append (Table.all'Access);
end Register_Table;
-- ------------------------------
-- Register the declaration of the given query in the model.
-- ------------------------------
procedure Register_Query (O : in out Model_Definition;
Table : access Gen.Model.Queries.Query_Definition'Class) is
begin
O.Register_Package (Table.Pkg_Name, Table.Package_Def);
Table.Package_Def.Queries.Append (Table.all'Access);
O.Queries.Append (Table.all'Access);
end Register_Query;
-- ------------------------------
-- Register the declaration of the given bean in the model.
-- ------------------------------
procedure Register_Bean (O : in out Model_Definition;
Bean : access Gen.Model.Beans.Bean_Definition'Class) is
begin
O.Register_Package (Bean.Pkg_Name, Bean.Package_Def);
Bean.Package_Def.Beans.Append (Bean.all'Access);
O.Queries.Append (Bean.all'Access);
end Register_Bean;
-- ------------------------------
-- Register or find the package knowing its name
-- ------------------------------
procedure Register_Package (O : in out Model_Definition;
Name : in Unbounded_String;
Result : out Package_Definition_Access) is
Pkg : constant String := Util.Strings.Transforms.To_Upper_Case (To_String (Name));
Key : constant Unbounded_String := To_Unbounded_String (Pkg);
Pos : constant Package_Map.Cursor := O.Packages.Find (Key);
begin
if not Package_Map.Has_Element (Pos) then
declare
Map : Ada.Strings.Maps.Character_Mapping;
Base_Name : Unbounded_String;
begin
Map := Ada.Strings.Maps.To_Mapping (From => ".", To => "-");
Base_Name := Translate (Name, Map);
Result := new Package_Definition;
Result.Pkg_Name := Name;
Result.Tables_Bean := Util.Beans.Objects.To_Object (Result.Tables'Access,
Util.Beans.Objects.STATIC);
Util.Strings.Transforms.To_Lower_Case (To_String (Base_Name),
Result.Base_Name);
O.Packages.Insert (Key, Result);
Log.Debug ("Ada package '{0}' registered", Name);
end;
else
Result := Package_Map.Element (Pos);
end if;
end Register_Package;
-- ------------------------------
-- Returns True if the model contains at least one package.
-- ------------------------------
function Has_Packages (O : in Model_Definition) return Boolean is
begin
return not O.Packages.Is_Empty;
end Has_Packages;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (O : in out Package_Definition) is
use Gen.Model.Tables;
procedure Prepare_Table (Table : in Table_Definition_Access);
procedure Prepare_Tables (Tables : in Table_List.List_Definition);
Used_Types : Gen.Utils.String_Set.Set;
T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Used_Types'Unchecked_Access;
procedure Prepare_Table (Table : in Table_Definition_Access) is
C : Column_List.Cursor := Table.Members.First;
begin
Table.Prepare;
-- Walk the columns to get their type.
while Column_List.Has_Element (C) loop
declare
Col : constant Column_Definition_Access := Column_List.Element (C);
T : constant String := To_String (Col.Type_Name);
Name : constant String := Gen.Utils.Get_Package_Name (T);
begin
if not Col.Is_Basic_Type and Name'Length > 0 and Name /= O.Pkg_Name then
Used_Types.Include (To_Unbounded_String (Name));
elsif T = "Time" or T = "Date" or T = "Timestamp" or T = "Nullable_Time" then
O.Uses_Calendar_Time := True;
end if;
end;
Column_List.Next (C);
end loop;
end Prepare_Table;
procedure Prepare_Tables (Tables : in Table_List.List_Definition) is
Table_Iter : Table_List.Cursor := Tables.First;
begin
while Table_List.Has_Element (Table_Iter) loop
declare
Table : constant Definition_Access := Table_List.Element (Table_Iter);
begin
if Table.all in Table_Definition'Class then
Prepare_Table (Table_Definition_Access (Table));
else
Table.Prepare;
end if;
end;
Table_List.Next (Table_Iter);
end loop;
end Prepare_Tables;
begin
Log.Info ("Preparing package {0}", O.Pkg_Name);
O.Used := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC);
O.Used_Types.Row := 0;
O.Used_Types.Values.Clear;
O.Uses_Calendar_Time := False;
O.Enums.Sort;
O.Queries.Sort;
Prepare_Tables (O.Enums);
Prepare_Tables (O.Tables);
Prepare_Tables (O.Queries);
declare
P : Gen.Utils.String_Set.Cursor := Used_Types.First;
begin
while Gen.Utils.String_Set.Has_Element (P) loop
declare
Name : constant Unbounded_String := Gen.Utils.String_Set.Element (P);
begin
Log.Info ("with {0}", Name);
O.Used_Types.Values.Append (Util.Beans.Objects.To_Object (Name));
end;
Gen.Utils.String_Set.Next (P);
end loop;
end;
end Prepare;
-- ------------------------------
-- Initialize the package instance
-- ------------------------------
overriding
procedure Initialize (O : in out Package_Definition) is
use Util.Beans.Objects;
begin
O.Enums_Bean := Util.Beans.Objects.To_Object (O.Enums'Unchecked_Access, STATIC);
O.Tables_Bean := Util.Beans.Objects.To_Object (O.Tables'Unchecked_Access, STATIC);
O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access, STATIC);
O.Beans_Bean := Util.Beans.Objects.To_Object (O.Beans'Unchecked_Access, STATIC);
O.Used := Util.Beans.Objects.To_Object (O.Used_Types'Unchecked_Access, STATIC);
end Initialize;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : List_Object) return Natural is
begin
Log.Debug ("Length {0}", Natural'Image (Natural (From.Values.Length)));
return Natural (From.Values.Length);
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out List_Object;
Index : in Natural) is
begin
Log.Debug ("Setting row {0}", Natural'Image (Index));
From.Row := Index;
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : List_Object) return Util.Beans.Objects.Object is
begin
Log.Debug ("Getting row {0}", Natural'Image (From.Row));
return From.Values.Element (From.Row - 1);
end Get_Row;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in List_Object;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
pragma Unreferenced (Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Model_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "tables" then
return From.Tables_Bean;
elsif Name = "dirname" then
return Util.Beans.Objects.To_Object (From.Dir_Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the directory name associated with the model. This directory name allows to
-- save and build a model in separate directories for the application, the unit tests
-- and others.
-- ------------------------------
procedure Set_Dirname (O : in out Model_Definition;
Target_Dir : in String;
Model_Dir : in String) is
begin
O.Dir_Name := To_Unbounded_String (Target_Dir);
O.DB_Name := To_Unbounded_String (Model_Dir);
end Set_Dirname;
-- ------------------------------
-- Get the directory name associated with the model.
-- ------------------------------
function Get_Dirname (O : in Model_Definition) return String is
begin
return To_String (O.Dir_Name);
end Get_Dirname;
-- ------------------------------
-- Get the directory name which contains the model.
-- ------------------------------
function Get_Model_Directory (O : in Model_Definition) return String is
begin
return To_String (O.DB_Name);
end Get_Model_Directory;
-- ------------------------------
-- Initialize the model definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Model_Definition) is
T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Tables'Unchecked_Access;
begin
O.Tables_Bean := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC);
O.Dir_Name := To_Unbounded_String ("src");
end Initialize;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (O : in out Model_Definition) is
Iter : Package_Cursor := O.Packages.First;
begin
while Has_Element (Iter) loop
Element (Iter).Prepare;
Next (Iter);
end loop;
O.Tables.Sort;
end Prepare;
-- ------------------------------
-- Get the first package of the model definition.
-- ------------------------------
function First (From : Model_Definition) return Package_Cursor is
begin
return From.Packages.First;
end First;
-- ------------------------------
-- Register a type mapping. The <b>From</b> type describes a type in the XML
-- configuration files (hibernate, query, ...) and the <b>To</b> represents the
-- corresponding Ada type.
-- ------------------------------
procedure Register_Type (O : in out Model_Definition;
From : in String;
To : in String) is
begin
null;
end Register_Type;
end Gen.Model.Packages;
|
-----------------------------------------------------------------------
-- gen-model-packages -- Packages holding model, query representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Maps;
with Gen.Utils;
with Gen.Model.Enums;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Gen.Model.Mappings;
with Gen.Model.Beans;
with Util.Strings;
with Util.Strings.Transforms;
with Util.Log.Loggers;
package body Gen.Model.Packages is
use type DOM.Core.Node;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Packages");
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Package_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (From.Pkg_Name);
elsif Name = "package" then
return Util.Beans.Objects.To_Object (From.Base_Name);
elsif Name = "tables" then
return From.Tables_Bean;
elsif Name = "enums" then
return From.Enums_Bean;
elsif Name = "queries" then
return From.Queries_Bean;
elsif Name = "beans" then
return From.Beans_Bean;
elsif Name = "usedTypes" then
return From.Used;
elsif Name = "useCalendarTime" then
return Util.Beans.Objects.To_Object (From.Uses_Calendar_Time);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Register the declaration of the given enum in the model.
-- ------------------------------
procedure Register_Enum (O : in out Model_Definition;
Enum : access Gen.Model.Enums.Enum_Definition'Class) is
Name : constant String := Enum.Get_Name;
begin
Log.Info ("Registering enum {0}", Name);
O.Register_Package (Enum.Pkg_Name, Enum.Package_Def);
if Enum.Package_Def.Enums.Find (Name) /= null then
raise Name_Exist with "Enum '" & Name & "' already defined";
end if;
Enum.Package_Def.Enums.Append (Enum.all'Access);
O.Enums.Append (Enum.all'Access);
Gen.Model.Mappings.Register_Type (To_String (Enum.Name), Enum.all'Access,
Gen.Model.Mappings.T_ENUM);
end Register_Enum;
-- ------------------------------
-- Register the declaration of the given table in the model.
-- ------------------------------
procedure Register_Table (O : in out Model_Definition;
Table : access Gen.Model.Tables.Table_Definition'Class) is
Name : constant String := Table.Get_Name;
begin
Log.Info ("Registering table {0}", Name);
O.Register_Package (Table.Pkg_Name, Table.Package_Def);
if Table.Package_Def.Tables.Find (Name) /= null then
raise Name_Exist with "Table '" & Name & "' already defined";
end if;
Table.Package_Def.Tables.Append (Table.all'Access);
O.Tables.Append (Table.all'Access);
end Register_Table;
-- ------------------------------
-- Register the declaration of the given query in the model.
-- ------------------------------
procedure Register_Query (O : in out Model_Definition;
Table : access Gen.Model.Queries.Query_Definition'Class) is
begin
O.Register_Package (Table.Pkg_Name, Table.Package_Def);
Table.Package_Def.Queries.Append (Table.all'Access);
O.Queries.Append (Table.all'Access);
end Register_Query;
-- ------------------------------
-- Register the declaration of the given bean in the model.
-- ------------------------------
procedure Register_Bean (O : in out Model_Definition;
Bean : access Gen.Model.Beans.Bean_Definition'Class) is
begin
O.Register_Package (Bean.Pkg_Name, Bean.Package_Def);
Bean.Package_Def.Beans.Append (Bean.all'Access);
O.Queries.Append (Bean.all'Access);
end Register_Bean;
-- ------------------------------
-- Register or find the package knowing its name
-- ------------------------------
procedure Register_Package (O : in out Model_Definition;
Name : in Unbounded_String;
Result : out Package_Definition_Access) is
Pkg : constant String := Util.Strings.Transforms.To_Upper_Case (To_String (Name));
Key : constant Unbounded_String := To_Unbounded_String (Pkg);
Pos : constant Package_Map.Cursor := O.Packages.Find (Key);
begin
if not Package_Map.Has_Element (Pos) then
declare
Map : Ada.Strings.Maps.Character_Mapping;
Base_Name : Unbounded_String;
begin
Map := Ada.Strings.Maps.To_Mapping (From => ".", To => "-");
Base_Name := Translate (Name, Map);
Result := new Package_Definition;
Result.Pkg_Name := Name;
Result.Tables_Bean := Util.Beans.Objects.To_Object (Result.Tables'Access,
Util.Beans.Objects.STATIC);
Util.Strings.Transforms.To_Lower_Case (To_String (Base_Name),
Result.Base_Name);
O.Packages.Insert (Key, Result);
Log.Debug ("Ada package '{0}' registered", Name);
end;
else
Result := Package_Map.Element (Pos);
end if;
end Register_Package;
-- ------------------------------
-- Returns True if the model contains at least one package.
-- ------------------------------
function Has_Packages (O : in Model_Definition) return Boolean is
begin
return not O.Packages.Is_Empty;
end Has_Packages;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (O : in out Package_Definition) is
use Gen.Model.Tables;
procedure Prepare_Table (Table : in Table_Definition_Access);
procedure Prepare_Tables (Tables : in Table_List.List_Definition);
Used_Types : Gen.Utils.String_Set.Set;
T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Used_Types'Unchecked_Access;
procedure Prepare_Table (Table : in Table_Definition_Access) is
C : Column_List.Cursor := Table.Members.First;
begin
Table.Prepare;
-- Walk the columns to get their type.
while Column_List.Has_Element (C) loop
declare
Col : constant Column_Definition_Access := Column_List.Element (C);
T : constant String := To_String (Col.Type_Name);
Name : constant String := Gen.Utils.Get_Package_Name (T);
begin
if not Col.Is_Basic_Type and Name'Length > 0 and Name /= O.Pkg_Name then
Used_Types.Include (To_Unbounded_String (Name));
elsif T = "Time" or T = "Date" or T = "Timestamp" or T = "Nullable_Time" then
O.Uses_Calendar_Time := True;
end if;
end;
Column_List.Next (C);
end loop;
end Prepare_Table;
procedure Prepare_Tables (Tables : in Table_List.List_Definition) is
Table_Iter : Table_List.Cursor := Tables.First;
begin
while Table_List.Has_Element (Table_Iter) loop
declare
Table : constant Definition_Access := Table_List.Element (Table_Iter);
begin
if Table.all in Table_Definition'Class then
Prepare_Table (Table_Definition_Access (Table));
else
Table.Prepare;
end if;
end;
Table_List.Next (Table_Iter);
end loop;
end Prepare_Tables;
begin
Log.Info ("Preparing package {0}", O.Pkg_Name);
O.Used := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC);
O.Used_Types.Row := 0;
O.Used_Types.Values.Clear;
O.Uses_Calendar_Time := False;
O.Enums.Sort;
O.Queries.Sort;
Prepare_Tables (O.Enums);
Prepare_Tables (O.Tables);
Prepare_Tables (O.Queries);
Prepare_Tables (O.Beans);
declare
P : Gen.Utils.String_Set.Cursor := Used_Types.First;
begin
while Gen.Utils.String_Set.Has_Element (P) loop
declare
Name : constant Unbounded_String := Gen.Utils.String_Set.Element (P);
begin
Log.Info ("with {0}", Name);
O.Used_Types.Values.Append (Util.Beans.Objects.To_Object (Name));
end;
Gen.Utils.String_Set.Next (P);
end loop;
end;
end Prepare;
-- ------------------------------
-- Initialize the package instance
-- ------------------------------
overriding
procedure Initialize (O : in out Package_Definition) is
use Util.Beans.Objects;
begin
O.Enums_Bean := Util.Beans.Objects.To_Object (O.Enums'Unchecked_Access, STATIC);
O.Tables_Bean := Util.Beans.Objects.To_Object (O.Tables'Unchecked_Access, STATIC);
O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access, STATIC);
O.Beans_Bean := Util.Beans.Objects.To_Object (O.Beans'Unchecked_Access, STATIC);
O.Used := Util.Beans.Objects.To_Object (O.Used_Types'Unchecked_Access, STATIC);
end Initialize;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : List_Object) return Natural is
begin
Log.Debug ("Length {0}", Natural'Image (Natural (From.Values.Length)));
return Natural (From.Values.Length);
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out List_Object;
Index : in Natural) is
begin
Log.Debug ("Setting row {0}", Natural'Image (Index));
From.Row := Index;
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : List_Object) return Util.Beans.Objects.Object is
begin
Log.Debug ("Getting row {0}", Natural'Image (From.Row));
return From.Values.Element (From.Row - 1);
end Get_Row;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in List_Object;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From);
pragma Unreferenced (Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Model_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "tables" then
return From.Tables_Bean;
elsif Name = "dirname" then
return Util.Beans.Objects.To_Object (From.Dir_Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the directory name associated with the model. This directory name allows to
-- save and build a model in separate directories for the application, the unit tests
-- and others.
-- ------------------------------
procedure Set_Dirname (O : in out Model_Definition;
Target_Dir : in String;
Model_Dir : in String) is
begin
O.Dir_Name := To_Unbounded_String (Target_Dir);
O.DB_Name := To_Unbounded_String (Model_Dir);
end Set_Dirname;
-- ------------------------------
-- Get the directory name associated with the model.
-- ------------------------------
function Get_Dirname (O : in Model_Definition) return String is
begin
return To_String (O.Dir_Name);
end Get_Dirname;
-- ------------------------------
-- Get the directory name which contains the model.
-- ------------------------------
function Get_Model_Directory (O : in Model_Definition) return String is
begin
return To_String (O.DB_Name);
end Get_Model_Directory;
-- ------------------------------
-- Initialize the model definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Model_Definition) is
T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Tables'Unchecked_Access;
begin
O.Tables_Bean := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC);
O.Dir_Name := To_Unbounded_String ("src");
end Initialize;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (O : in out Model_Definition) is
Iter : Package_Cursor := O.Packages.First;
begin
while Has_Element (Iter) loop
Element (Iter).Prepare;
Next (Iter);
end loop;
O.Tables.Sort;
end Prepare;
-- ------------------------------
-- Get the first package of the model definition.
-- ------------------------------
function First (From : Model_Definition) return Package_Cursor is
begin
return From.Packages.First;
end First;
-- ------------------------------
-- Register a type mapping. The <b>From</b> type describes a type in the XML
-- configuration files (hibernate, query, ...) and the <b>To</b> represents the
-- corresponding Ada type.
-- ------------------------------
procedure Register_Type (O : in out Model_Definition;
From : in String;
To : in String) is
begin
null;
end Register_Type;
end Gen.Model.Packages;
|
Prepare the Ada beans by invoking the Prepare operation on each of them
|
Prepare the Ada beans by invoking the Prepare operation on each of them
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
9e4b06a21cf3ac5c875504d48f7283b709291384
|
src/security-controllers-roles.ads
|
src/security-controllers-roles.ads
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
with Security.Permissions;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
package Security.Controllers.Roles is
-- ------------------------------
-- Security Controller
-- ------------------------------
-- The <b>Role_Controller</b> implements a simple role based permissions check.
-- The permission is granted if the user has the role defined by the controller.
type Role_Controller (Count : Positive) is limited new Controller with record
Roles : Permissions.Role_Type_Array (1 .. Count);
end record;
type Role_Controller_Access is access all Role_Controller'Class;
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last));
Count : Natural := 0;
Manager : Security.Permissions.Permission_Manager_Access;
end record;
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Controller_Config;
end Reader_Config;
end Security.Controllers.Roles;
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
with Security.Permissions;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Security.Policies.Roles;
package Security.Controllers.Roles is
-- ------------------------------
-- Security Controller
-- ------------------------------
-- The <b>Role_Controller</b> implements a simple role based permissions check.
-- The permission is granted if the user has the role defined by the controller.
type Role_Controller (Count : Positive) is limited new Controller with record
Roles : Policies.Roles.Role_Type_Array (1 .. Count);
end record;
type Role_Controller_Access is access all Role_Controller'Class;
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last));
Count : Natural := 0;
Manager : Security.Permissions.Permission_Manager_Access;
end record;
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Controller_Config;
end Reader_Config;
end Security.Controllers.Roles;
|
Use the Security.Policies.Roles package
|
Use the Security.Policies.Roles package
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
8215233cf455019195605e8e768a5dd23e7a6d02
|
src/wiki-render-text.adb
|
src/wiki-render-text.adb
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
package body Wiki.Render.Text is
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the no-newline mode to produce a single line text (disabled by default).
-- ------------------------------
procedure Set_No_Newline (Engine : in out Text_Renderer;
Enable : in Boolean) is
begin
Engine.No_Newline := Enable;
end Set_No_Newline;
-- ------------------------------
-- Emit a new line.
-- ------------------------------
procedure New_Line (Document : in out Text_Renderer) is
begin
if not Document.No_Newline then
Document.Output.Write (Wiki.Helpers.LF);
end if;
Document.Empty_Line := True;
end New_Line;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
procedure Add_Line_Break (Document : in out Text_Renderer) is
begin
if not Document.No_Newline then
Document.Output.Write (Wiki.Helpers.LF);
end if;
Document.Empty_Line := True;
end Add_Line_Break;
-- ------------------------------
-- Render a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Render_Blockquote (Engine : in out Text_Renderer;
Level : in Natural) is
begin
Engine.Close_Paragraph;
for I in 1 .. Level loop
Engine.Output.Write (" ");
end loop;
end Render_Blockquote;
-- ------------------------------
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Render_List_Item (Engine : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean) is
pragma Unreferenced (Level, Ordered);
begin
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
end Render_List_Item;
procedure Close_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Has_Paragraph then
Document.Add_Line_Break;
end if;
Document.Has_Paragraph := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Need_Paragraph then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
end Open_Paragraph;
-- ------------------------------
-- Render a link.
-- ------------------------------
procedure Render_Link (Engine : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List) is
Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href");
begin
Engine.Open_Paragraph;
if Title'Length /= 0 then
Engine.Output.Write (Title);
end if;
if Title /= Href and Href'Length /= 0 then
if Title'Length /= 0 then
Engine.Output.Write (" (");
end if;
Engine.Output.Write (Href);
if Title'Length /= 0 then
Engine.Output.Write (")");
end if;
end if;
Engine.Empty_Line := False;
end Render_Link;
-- ------------------------------
-- Render an image.
-- ------------------------------
procedure Render_Image (Engine : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List) is
Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc");
begin
Engine.Open_Paragraph;
if Title'Length > 0 then
Engine.Output.Write (Title);
end if;
if Title'Length > 0 and Desc'Length > 0 then
Engine.Output.Write (' ');
end if;
if Desc'Length > 0 then
Engine.Output.Write (Desc);
end if;
Engine.Empty_Line := False;
end Render_Image;
-- ------------------------------
-- Render a text block that is pre-formatted.
-- ------------------------------
procedure Render_Preformatted (Engine : in out Text_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
pragma Unreferenced (Format);
begin
Engine.Close_Paragraph;
Engine.Output.Write (Text);
Engine.Empty_Line := False;
end Render_Preformatted;
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Close_Paragraph;
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Output.Write (Node.Header);
Engine.Add_Line_Break;
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Add_Line_Break;
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Output.Write ("---------------------------------------------------------");
Engine.Add_Line_Break;
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
Engine.Add_Line_Break;
when Wiki.Nodes.N_NEWLINE =>
if not Engine.No_Newline then
Engine.Output.Write (Wiki.Helpers.LF);
else
Engine.Output.Write (' ');
end if;
when Wiki.Nodes.N_INDENT =>
Engine.Indent_Level := Node.Level;
when Wiki.Nodes.N_BLOCKQUOTE =>
Engine.Render_Blockquote (Node.Level);
when Wiki.Nodes.N_LIST =>
Engine.Render_List_Item (Node.Level, False);
when Wiki.Nodes.N_NUM_LIST =>
Engine.Render_List_Item (Node.Level, True);
when Wiki.Nodes.N_TEXT =>
if Engine.Empty_Line and Engine.Indent_Level /= 0 then
for I in 1 .. Engine.Indent_Level loop
Engine.Output.Write (' ');
end loop;
end if;
Engine.Output.Write (Node.Text);
Engine.Empty_Line := False;
when Wiki.Nodes.N_QUOTE =>
Engine.Open_Paragraph;
Engine.Output.Write (Node.Title);
Engine.Empty_Line := False;
when Wiki.Nodes.N_LINK =>
Engine.Render_Link (Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
Engine.Render_Image (Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_PREFORMAT =>
Engine.Render_Preformatted (Node.Preformatted, "");
when Wiki.Nodes.N_TAG_START =>
if Node.Children /= null then
if Node.Tag_Start = Wiki.DT_TAG then
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
elsif Node.Tag_Start = Wiki.DD_TAG then
Engine.Close_Paragraph;
Engine.Empty_Line := True;
Engine.Indent_Level := 4;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
else
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.DL_TAG then
Engine.Close_Paragraph;
Engine.New_Line;
end if;
end if;
end if;
when others =>
null;
end case;
end Render;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document) is
pragma Unreferenced (Doc);
begin
Engine.Close_Paragraph;
end Finish;
end Wiki.Render.Text;
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 2019, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
with Util.Strings;
package body Wiki.Render.Text is
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the no-newline mode to produce a single line text (disabled by default).
-- ------------------------------
procedure Set_No_Newline (Engine : in out Text_Renderer;
Enable : in Boolean) is
begin
Engine.No_Newline := Enable;
end Set_No_Newline;
-- ------------------------------
-- Emit a new line.
-- ------------------------------
procedure New_Line (Document : in out Text_Renderer) is
begin
if not Document.No_Newline then
Document.Output.Write (Wiki.Helpers.LF);
end if;
Document.Empty_Line := True;
end New_Line;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
procedure Add_Line_Break (Document : in out Text_Renderer) is
begin
if not Document.No_Newline then
Document.Output.Write (Wiki.Helpers.LF);
end if;
Document.Empty_Line := True;
Document.Current_Indent := 0;
end Add_Line_Break;
-- ------------------------------
-- Render a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Render_Blockquote (Engine : in out Text_Renderer;
Level : in Natural) is
begin
Engine.Close_Paragraph;
for I in 1 .. Level loop
Engine.Output.Write (" ");
end loop;
end Render_Blockquote;
procedure Render_List_Start (Engine : in out Text_Renderer;
Tag : in String;
Level : in Natural) is
begin
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
if not Engine.No_Newline then
Engine.Output.Write (Wiki.Helpers.LF);
end if;
Engine.List_Index := Engine.List_Index + 1;
Engine.List_Levels (Engine.List_Index) := Level;
Engine.Indent_Level := Engine.Indent_Level + 2;
end Render_List_Start;
procedure Render_List_End (Engine : in out Text_Renderer;
Tag : in String) is
begin
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
Engine.List_Index := Engine.List_Index - 1;
Engine.Indent_Level := Engine.Indent_Level - 2;
end Render_List_End;
-- ------------------------------
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Render_List_Item_Start (Engine : in out Text_Renderer) is
begin
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
if Engine.List_Levels (Engine.List_Index) > 0 then
Engine.Render_Paragraph (Strings.To_Wstring (Util.Strings.Image (Engine.List_Levels (Engine.List_Index))));
Engine.List_Levels (Engine.List_Index) := Engine.List_Levels (Engine.List_index) + 1;
Engine.Render_Paragraph (") ");
Engine.Indent_Level := Engine.Indent_Level + 4;
else
Engine.Render_Paragraph ("- ");
Engine.Indent_Level := Engine.Indent_Level + 2;
end if;
end Render_List_Item_Start;
procedure Render_List_Item_End (Engine : in out Text_Renderer) is
begin
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
if Engine.List_Levels (Engine.List_Index) > 0 then
Engine.Indent_Level := Engine.Indent_Level - 4;
else
Engine.Indent_Level := Engine.Indent_Level - 2;
end if;
end Render_List_Item_End;
procedure Close_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Has_Paragraph then
Document.Add_Line_Break;
end if;
Document.Has_Paragraph := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Need_Paragraph then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
end Open_Paragraph;
-- ------------------------------
-- Render a link.
-- ------------------------------
procedure Render_Link (Engine : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List) is
Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href");
begin
Engine.Open_Paragraph;
if Title'Length /= 0 then
Engine.Output.Write (Title);
end if;
if Title /= Href and Href'Length /= 0 then
if Title'Length /= 0 then
Engine.Output.Write (" (");
end if;
Engine.Output.Write (Href);
if Title'Length /= 0 then
Engine.Output.Write (")");
end if;
end if;
Engine.Empty_Line := False;
end Render_Link;
-- ------------------------------
-- Render an image.
-- ------------------------------
procedure Render_Image (Engine : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List) is
Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc");
begin
Engine.Open_Paragraph;
if Title'Length > 0 then
Engine.Output.Write (Title);
end if;
if Title'Length > 0 and Desc'Length > 0 then
Engine.Output.Write (' ');
end if;
if Desc'Length > 0 then
Engine.Output.Write (Desc);
end if;
Engine.Empty_Line := False;
end Render_Image;
-- ------------------------------
-- Render a text block that is pre-formatted.
-- ------------------------------
procedure Render_Preformatted (Engine : in out Text_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
pragma Unreferenced (Format);
begin
Engine.Close_Paragraph;
Engine.Output.Write (Text);
Engine.Empty_Line := False;
end Render_Preformatted;
-- ------------------------------
-- Render a text block indenting the text if necessary.
-- ------------------------------
procedure Render_Paragraph (Engine : in out Text_Renderer;
Text : in Wiki.Strings.WString) is
begin
for C of Text loop
if C = Helpers.LF then
Engine.Empty_Line := True;
Engine.Current_Indent := 0;
Engine.Output.Write (C);
else
while Engine.Current_Indent < Engine.Indent_Level loop
Engine.Output.Write (' ');
Engine.Current_Indent := Engine.Current_Indent + 1;
end loop;
Engine.Output.Write (C);
Engine.Empty_Line := False;
Engine.Current_Indent := Engine.Current_Indent + 1;
Engine.Has_Paragraph := True;
end if;
end loop;
end Render_Paragraph;
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Close_Paragraph;
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Output.Write (Node.Header);
Engine.Add_Line_Break;
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Add_Line_Break;
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Output.Write ("---------------------------------------------------------");
Engine.Add_Line_Break;
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
Engine.Add_Line_Break;
when Wiki.Nodes.N_NEWLINE =>
if not Engine.No_Newline then
Engine.Output.Write (Wiki.Helpers.LF);
else
Engine.Output.Write (' ');
end if;
when Wiki.Nodes.N_INDENT =>
Engine.Indent_Level := Node.Level;
when Wiki.Nodes.N_BLOCKQUOTE =>
Engine.Render_Blockquote (Node.Level);
when Wiki.Nodes.N_LIST_START =>
Engine.Render_List_Start ("o", 0);
when Wiki.Nodes.N_NUM_LIST_START =>
Engine.Render_List_Start (".", Node.Level);
when Wiki.Nodes.N_LIST_END =>
Engine.Render_List_End ("");
when Wiki.Nodes.N_NUM_LIST_END =>
Engine.Render_List_End ("");
when Wiki.Nodes.N_LIST_ITEM =>
Engine.Render_List_Item_Start;
when Wiki.Nodes.N_LIST_ITEM_END =>
Engine.Render_List_Item_End;
when Wiki.Nodes.N_TEXT =>
Engine.Render_Paragraph (Node.Text);
when Wiki.Nodes.N_QUOTE =>
Engine.Open_Paragraph;
Engine.Output.Write (Node.Title);
Engine.Empty_Line := False;
when Wiki.Nodes.N_LINK =>
Engine.Render_Link (Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
Engine.Render_Image (Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_PREFORMAT =>
Engine.Render_Preformatted (Node.Preformatted, "");
when Wiki.Nodes.N_TAG_START =>
if Node.Children /= null then
if Node.Tag_Start = Wiki.DT_TAG then
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
elsif Node.Tag_Start = Wiki.DD_TAG then
Engine.Close_Paragraph;
Engine.Empty_Line := True;
Engine.Indent_Level := 4;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Indent_Level := 0;
else
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.DL_TAG then
Engine.Close_Paragraph;
Engine.New_Line;
end if;
end if;
end if;
when others =>
null;
end case;
end Render;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Engine : in out Text_Renderer;
Doc : in Wiki.Documents.Document) is
pragma Unreferenced (Doc);
begin
Engine.Close_Paragraph;
end Finish;
end Wiki.Render.Text;
|
Add support to render lists and provide a better presentation
|
Add support to render lists and provide a better presentation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
df50a8d2c43acd91c29a0e4acd32877e48e546ce
|
src/asf-models-selects.adb
|
src/asf-models-selects.adb
|
-----------------------------------------------------------------------
-- asf-models-selects -- Data model for UISelectOne and UISelectMany
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
package body ASF.Models.Selects is
-- ------------------------------
-- Return an Object from the select item record.
-- Returns a NULL object if the item is empty.
-- ------------------------------
function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object is
begin
if Item.Item.Is_Null then
return Util.Beans.Objects.Null_Object;
else
declare
Bean : constant Select_Item_Access := new Select_Item;
begin
Bean.all := Item;
return Util.Beans.Objects.To_Object (Bean.all'Access);
end;
end if;
end To_Object;
-- ------------------------------
-- Return the <b>Select_Item</b> instance from a generic bean object.
-- Returns an empty item if the object does not hold a <b>Select_Item</b>.
-- ------------------------------
function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Object);
Result : Select_Item;
begin
if Bean = null then
return Result;
end if;
if not (Bean.all in Select_Item'Class) then
return Result;
end if;
Result := Select_Item (Bean.all);
return Result;
end To_Select_Item;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label and value.
-- ------------------------------
function Create_Select_Item (Label : in String;
Value : in String;
Description : in String := "";
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
use Ada.Characters.Conversions;
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
Item.Label := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Label));
Item.Value := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Value));
Item.Description := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Description));
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label and value.
-- ------------------------------
function Create_Select_Item_Wide (Label : in Wide_Wide_String;
Value : in Wide_Wide_String;
Description : in Wide_Wide_String := "";
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
Item.Label := To_Unbounded_Wide_Wide_String (Label);
Item.Value := To_Unbounded_Wide_Wide_String (Value);
Item.Description := To_Unbounded_Wide_Wide_String (Description);
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item_Wide;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label, value and description.
-- The objects are converted to a wide wide string. The empty string is used if they
-- are null.
-- ------------------------------
function Create_Select_Item (Label : in Util.Beans.Objects.Object;
Value : in Util.Beans.Objects.Object;
Description : in Util.Beans.Objects.Object;
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
use Util.Beans.Objects;
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
if not Is_Null (Label) then
Item.Label := To_Unbounded_Wide_Wide_String (Label);
end if;
if not Is_Null (Value) then
Item.Value := To_Unbounded_Wide_Wide_String (Value);
end if;
if not Is_Null (Description) then
Item.Description := To_Unbounded_Wide_Wide_String (Description);
end if;
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item;
-- ------------------------------
-- Get the item label.
-- ------------------------------
function Get_Label (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Label);
end if;
end Get_Label;
-- ------------------------------
-- Get the item value.
-- ------------------------------
function Get_Value (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Value);
end if;
end Get_Value;
-- ------------------------------
-- Get the item description.
-- ------------------------------
function Get_Description (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Description);
end if;
end Get_Description;
-- ------------------------------
-- Returns true if the item is disabled.
-- ------------------------------
function Is_Disabled (Item : in Select_Item) return Boolean is
begin
if Item.Item.Is_Null then
return False;
else
return Item.Item.Value.Disabled;
end if;
end Is_Disabled;
-- ------------------------------
-- Returns true if the label must be escaped using HTML escape rules.
-- ------------------------------
function Is_Escaped (Item : in Select_Item) return Boolean is
begin
if Item.Item.Is_Null then
return False;
else
return Item.Item.Value.Escape;
end if;
end Is_Escaped;
-- ------------------------------
-- Returns true if the select item component is empty.
-- ------------------------------
function Is_Empty (Item : in Select_Item) return Boolean is
begin
return Item.Item.Is_Null;
end Is_Empty;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Select_Item;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Item.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Select_Item_Record_Access := From.Item.Value;
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (Item.Label);
elsif Name = "value" then
return Util.Beans.Objects.To_Object (Item.Value);
elsif Name = "description" then
return Util.Beans.Objects.To_Object (Item.Description);
elsif Name = "disabled" then
return Util.Beans.Objects.To_Object (Item.Disabled);
elsif Name = "escaped" then
return Util.Beans.Objects.To_Object (Item.Escape);
else
return Util.Beans.Objects.Null_Object;
end if;
end;
end Get_Value;
-- ------------------------------
-- Select Item List
-- ------------------------------
-- ------------------------------
-- Return an Object from the select item list.
-- Returns a NULL object if the list is empty.
-- ------------------------------
function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object is
begin
if Item.List.Is_Null then
return Util.Beans.Objects.Null_Object;
else
declare
Bean : constant Select_Item_List_Access := new Select_Item_List;
begin
Bean.all := Item;
return Util.Beans.Objects.To_Object (Bean.all'Access);
end;
end if;
end To_Object;
-- ------------------------------
-- Return the <b>Select_Item_List</b> instance from a generic bean object.
-- Returns an empty list if the object does not hold a <b>Select_Item_List</b>.
-- ------------------------------
function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Object);
Result : Select_Item_List;
begin
if Bean = null then
return Result;
end if;
if not (Bean.all in Select_Item_List'Class) then
return Result;
end if;
Result := Select_Item_List (Bean.all);
return Result;
end To_Select_Item_List;
-- ------------------------------
-- Get the number of items in the list.
-- ------------------------------
function Length (List : in Select_Item_List) return Natural is
begin
if List.List.Is_Null then
return 0;
else
return Natural (List.List.Value.List.Length);
end if;
end Length;
-- ------------------------------
-- Get the select item from the list
-- ------------------------------
function Get_Select_Item (List : in Select_Item_List'Class;
Pos : in Positive) return Select_Item is
begin
if List.List.Is_Null then
raise Constraint_Error with "Select item list is empty";
end if;
return List.List.Value.List.Element (Pos);
end Get_Select_Item;
-- ------------------------------
-- Add the item at the end of the list.
-- ------------------------------
procedure Append (List : in out Select_Item_List;
Item : in Select_Item'Class) is
begin
if List.List.Is_Null then
List.List := Select_Item_Vector_Refs.Create;
end if;
List.List.Value.all.List.Append (Select_Item (Item));
end Append;
-- ------------------------------
-- Add the item at the end of the list. This is a shortcut for
-- Append (Create_List_Item (Label, Value))
-- ------------------------------
procedure Append (List : in out Select_Item_List;
Label : in String;
Value : in String) is
begin
List.Append (Create_Select_Item (Label, Value));
end Append;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Select_Item_List;
Name : in String) return Util.Beans.Objects.Object is
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
end ASF.Models.Selects;
|
-----------------------------------------------------------------------
-- asf-models-selects -- Data model for UISelectOne and UISelectMany
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
package body ASF.Models.Selects is
-- ------------------------------
-- Return an Object from the select item record.
-- Returns a NULL object if the item is empty.
-- ------------------------------
function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object is
begin
if Item.Item.Is_Null then
return Util.Beans.Objects.Null_Object;
else
declare
Bean : constant Select_Item_Access := new Select_Item;
begin
Bean.all := Item;
return Util.Beans.Objects.To_Object (Bean.all'Access);
end;
end if;
end To_Object;
-- ------------------------------
-- Return the <b>Select_Item</b> instance from a generic bean object.
-- Returns an empty item if the object does not hold a <b>Select_Item</b>.
-- ------------------------------
function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Object);
Result : Select_Item;
begin
if Bean = null then
return Result;
end if;
if not (Bean.all in Select_Item'Class) then
return Result;
end if;
Result := Select_Item (Bean.all);
return Result;
end To_Select_Item;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label and value.
-- ------------------------------
function Create_Select_Item (Label : in String;
Value : in String;
Description : in String := "";
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
use Ada.Characters.Conversions;
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
Item.Label := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Label));
Item.Value := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Value));
Item.Description := To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (Description));
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label and value.
-- ------------------------------
function Create_Select_Item_Wide (Label : in Wide_Wide_String;
Value : in Wide_Wide_String;
Description : in Wide_Wide_String := "";
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
Item.Label := To_Unbounded_Wide_Wide_String (Label);
Item.Value := To_Unbounded_Wide_Wide_String (Value);
Item.Description := To_Unbounded_Wide_Wide_String (Description);
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item_Wide;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label, value and description.
-- The objects are converted to a wide wide string. The empty string is used if they
-- are null.
-- ------------------------------
function Create_Select_Item (Label : in Util.Beans.Objects.Object;
Value : in Util.Beans.Objects.Object;
Description : in Util.Beans.Objects.Object;
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
use Util.Beans.Objects;
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
if not Is_Null (Label) then
Item.Label := To_Unbounded_Wide_Wide_String (Label);
end if;
if not Is_Null (Value) then
Item.Value := To_Unbounded_Wide_Wide_String (Value);
end if;
if not Is_Null (Description) then
Item.Description := To_Unbounded_Wide_Wide_String (Description);
end if;
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item;
-- ------------------------------
-- Get the item label.
-- ------------------------------
function Get_Label (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Label);
end if;
end Get_Label;
-- ------------------------------
-- Get the item value.
-- ------------------------------
function Get_Value (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Value);
end if;
end Get_Value;
-- ------------------------------
-- Get the item description.
-- ------------------------------
function Get_Description (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Description);
end if;
end Get_Description;
-- ------------------------------
-- Returns true if the item is disabled.
-- ------------------------------
function Is_Disabled (Item : in Select_Item) return Boolean is
begin
if Item.Item.Is_Null then
return False;
else
return Item.Item.Value.Disabled;
end if;
end Is_Disabled;
-- ------------------------------
-- Returns true if the label must be escaped using HTML escape rules.
-- ------------------------------
function Is_Escaped (Item : in Select_Item) return Boolean is
begin
if Item.Item.Is_Null then
return False;
else
return Item.Item.Value.Escape;
end if;
end Is_Escaped;
-- ------------------------------
-- Returns true if the select item component is empty.
-- ------------------------------
function Is_Empty (Item : in Select_Item) return Boolean is
begin
return Item.Item.Is_Null;
end Is_Empty;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Select_Item;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Item.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Select_Item_Record_Access := From.Item.Value;
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (Item.Label);
elsif Name = "value" then
return Util.Beans.Objects.To_Object (Item.Value);
elsif Name = "description" then
return Util.Beans.Objects.To_Object (Item.Description);
elsif Name = "disabled" then
return Util.Beans.Objects.To_Object (Item.Disabled);
elsif Name = "escaped" then
return Util.Beans.Objects.To_Object (Item.Escape);
else
return Util.Beans.Objects.Null_Object;
end if;
end;
end Get_Value;
-- ------------------------------
-- Select Item List
-- ------------------------------
-- ------------------------------
-- Return an Object from the select item list.
-- Returns a NULL object if the list is empty.
-- ------------------------------
function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object is
begin
if Item.List.Is_Null then
return Util.Beans.Objects.Null_Object;
else
declare
Bean : constant Select_Item_List_Access := new Select_Item_List;
begin
Bean.all := Item;
return Util.Beans.Objects.To_Object (Bean.all'Access);
end;
end if;
end To_Object;
-- ------------------------------
-- Return the <b>Select_Item_List</b> instance from a generic bean object.
-- Returns an empty list if the object does not hold a <b>Select_Item_List</b>.
-- ------------------------------
function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Object);
Result : Select_Item_List;
begin
if Bean = null then
return Result;
end if;
if not (Bean.all in Select_Item_List'Class) then
return Result;
end if;
Result := Select_Item_List (Bean.all);
return Result;
end To_Select_Item_List;
-- ------------------------------
-- Get the number of items in the list.
-- ------------------------------
function Length (List : in Select_Item_List) return Natural is
begin
if List.List.Is_Null then
return 0;
else
return Natural (List.List.Value.List.Length);
end if;
end Length;
-- ------------------------------
-- Get the select item from the list
-- ------------------------------
function Get_Select_Item (List : in Select_Item_List'Class;
Pos : in Positive) return Select_Item is
begin
if List.List.Is_Null then
raise Constraint_Error with "Select item list is empty";
end if;
return List.List.Value.List.Element (Pos);
end Get_Select_Item;
-- ------------------------------
-- Add the item at the end of the list.
-- ------------------------------
procedure Append (List : in out Select_Item_List;
Item : in Select_Item'Class) is
begin
if List.List.Is_Null then
List.List := Select_Item_Vector_Refs.Create;
end if;
List.List.Value.all.List.Append (Select_Item (Item));
end Append;
-- ------------------------------
-- Add the item at the end of the list. This is a shortcut for
-- Append (Create_List_Item (Label, Value))
-- ------------------------------
procedure Append (List : in out Select_Item_List;
Label : in String;
Value : in String) is
begin
List.Append (Create_Select_Item (Label, Value));
end Append;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Select_Item_List;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
end ASF.Models.Selects;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
95d79942edd41c3cbed259f0c5a723728eb7c53d
|
awa/plugins/awa-counters/src/awa-counters.ads
|
awa/plugins/awa-counters/src/awa-counters.ads
|
-----------------------------------------------------------------------
-- awa-counters --
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Objects;
with ADO.Schemas;
with Util.Strings;
with AWA.Index_Arrays;
package AWA.Counters is
type Counter_Index_Type is new Natural;
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object <tt>Object</tt>.
procedure Increment (Counter : in Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class);
private
type Counter_Def is record
Table : ADO.Schemas.Class_Mapping_Access;
Field : Util.Strings.Name_Access;
end record;
function "=" (Left, Right : in Counter_Def) return Boolean;
function "<" (Left, Right : in Counter_Def) return Boolean;
function "&" (Left : in String;
Right : in Counter_Def) return String;
package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type, Counter_Def);
end AWA.Counters;
|
-----------------------------------------------------------------------
-- awa-counters --
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Objects;
with ADO.Schemas;
with Util.Strings;
with AWA.Index_Arrays;
package AWA.Counters is
type Counter_Index_Type is new Natural;
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object <tt>Object</tt>.
procedure Increment (Counter : in Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class);
-- Increment the global counter identified by <tt>Counter</tt>.
procedure Increment (Counter : in Counter_Index_Type);
private
type Counter_Def is record
Table : ADO.Schemas.Class_Mapping_Access;
Field : Util.Strings.Name_Access;
end record;
function "=" (Left, Right : in Counter_Def) return Boolean;
function "<" (Left, Right : in Counter_Def) return Boolean;
function "&" (Left : in String;
Right : in Counter_Def) return String;
package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type, Counter_Def);
end AWA.Counters;
|
Declare Increment procedure with single Counter parameter
|
Declare Increment procedure with single Counter parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b8a7669c8c5635c7fe8b3b89680af3af8ed168c9
|
src/ado-schemas-databases.adb
|
src/ado-schemas-databases.adb
|
-----------------------------------------------------------------------
-- 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 ADO.Drivers.Connections;
package body 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) is
procedure Process (Database : in out ADO.Drivers.Connections.Database_Connection'Class);
procedure Process (Database : in out ADO.Drivers.Connections.Database_Connection'Class) is
begin
Database.Create_Database (Config => Config,
Schema_Path => Schema_Path,
Messages => Messages);
end Process;
begin
Session.Access_Connection (Process'Access);
end Create_Database;
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 ADO.Drivers.Connections;
package body ADO.Schemas.Databases is
-- ------------------------------
-- Create the database and initialize it with the schema SQL file.
-- ------------------------------
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) is
Name : constant String := Config.Get_Driver;
Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name);
begin
Messages.Clear;
Driver.Create_Database (Admin => Admin,
Config => Config,
Schema_Path => Schema_Path,
Messages => Messages);
end Create_Database;
end ADO.Schemas.Databases;
|
Update the Create_Database operation to use the Data_Source as parameter, get the database driver and call the Create_Database on it
|
Update the Create_Database operation to use the Data_Source as parameter, get the
database driver and call the Create_Database on it
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
c3ad74c78cee07ca0306b0864fe112b28cfeee31
|
src/natools-smaz-tools.ads
|
src/natools-smaz-tools.ads
|
------------------------------------------------------------------------------
-- Copyright (c) 2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Smaz.Tools helps building and generating dictionary for use --
-- with its parent package. Note that the dictionary is intended to be --
-- generated and hard-coded, so the final client shouldn't need this --
-- package. --
------------------------------------------------------------------------------
with Ada.Containers.Indefinite_Doubly_Linked_Lists;
with Natools.S_Expressions;
private with Ada.Containers.Indefinite_Ordered_Maps;
private with Ada.Containers.Indefinite_Ordered_Sets;
private with Ada.Finalization;
package Natools.Smaz.Tools is
pragma Preelaborate;
package String_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists
(String);
procedure Read_List
(List : out String_Lists.List;
Descriptor : in out S_Expressions.Descriptor'Class);
-- Read atoms from Descriptor to fill List
function To_Dictionary
(List : in String_Lists.List;
Variable_Length_Verbatim : in Boolean)
return Dictionary
with Pre => String_Lists.Length (List) in 1 ..
Ada.Containers.Count_Type (Ada.Streams.Stream_Element'Last);
-- Build a Dictionary object from a string list
-- Note that Hash is set to a placeholder which uncinditionnally
-- raises Program_Error when called.
generic
with procedure Put_Line (Line : String);
procedure Print_Dictionary_In_Ada
(Dict : in Dictionary;
Hash_Image : in String := "TODO";
Max_Width : in Positive := 70;
First_Prefix : in String := " := (";
Prefix : in String := " ";
Half_Indent : in String := " ");
-- Output Ada code corresponding to the value of the dictionary.
-- Note that Prefix is the actual base indentation, while Half_Indent
-- is added beyond Prefix before values continued on another line.
-- Frist_Prefix is used instead of Prefix on the first line.
-- All the defaults value are what was used to generate the constant
-- in Natools.Smaz.Original.
function Remove_Element
(Dict : in Dictionary;
Index : in Ada.Streams.Stream_Element)
return Dictionary
with Pre => Index <= Dict.Dict_Last,
Post => Dict.Dict_Last = Remove_Element'Result.Dict_Last + 1
and then (Index = 0
or else (for all I in 0 .. Index - 1
=> Dict_Entry (Dict, I)
= Dict_Entry (Remove_Element'Result, I)))
and then (Index = Dict.Dict_Last
or else (for all I in Index .. Dict.Dict_Last - 1
=> Dict_Entry (Dict, I + 1)
= Dict_Entry (Remove_Element'Result, I)));
-- Return a new dictionary equal to Dict without element for Index
function Append_String
(Dict : in Dictionary;
Value : in String)
return Dictionary
with Pre => Dict.Dict_Last < Ada.Streams.Stream_Element'Last
and then Value'Length > 0,
Post => Dict.Dict_Last = Append_String'Result.Dict_Last - 1
and then (for all I in 0 .. Dict.Dict_Last
=> Dict_Entry (Dict, I)
= Dict_Entry (Append_String'Result, I))
and then Dict_Entry (Append_String'Result,
Append_String'Result.Dict_Last)
= Value;
-- Return a new dictionary with Value appended
List_For_Linear_Search : String_Lists.List;
function Linear_Search (Value : String) return Natural;
-- Function and data source for inefficient but dynamic function
-- that can be used with Dictionary.Hash.
procedure Set_Dictionary_For_Map_Search (Dict : in Dictionary);
function Map_Search (Value : String) return Natural;
-- Function and data source for logarithmic search using standard
-- ordered map, that can be used with Dictionary.Hash.
type Search_Trie is private;
procedure Initialize (Trie : out Search_Trie; Dict : in Dictionary);
function Search (Trie : in Search_Trie; Value : in String) return Natural;
-- Trie-based search in a dynamic dictionary, for lookup whose
-- speed-vs-memory is even more skewed towards speed.
procedure Set_Dictionary_For_Trie_Search (Dict : in Dictionary);
function Trie_Search (Value : String) return Natural;
-- Function and data source for trie-based search that can be
-- used with Dictionary.Hash.
type String_Count is range 0 .. 2 ** 31 - 1;
-- Type for a number of substring occurrences
package Methods is
type Enum is (Encoded, Frequency, Gain);
end Methods;
-- Evaluation methods to select words to remove or include
type Word_Counter is private;
-- Accumulate frequency/occurrence counts for a set of strings
procedure Add_Word
(Counter : in out Word_Counter;
Word : in String;
Count : in String_Count := 1);
-- Include Count number of occurrences of Word in Counter
procedure Add_Substrings
(Counter : in out Word_Counter;
Phrase : in String;
Min_Size : in Positive;
Max_Size : in Positive);
-- Include all the substrings of Phrase whose lengths are
-- between Min_Size and Max_Size.
procedure Add_Words
(Counter : in out Word_Counter;
Phrase : in String;
Min_Size : in Positive;
Max_Size : in Positive);
-- Add the "words" from Phrase into Counter, with a word being currently
-- defined as anything between ASCII blanks or punctuation,
-- or in other words [0-9A-Za-z\x80-\xFF]+
procedure Filter_By_Count
(Counter : in out Word_Counter;
Threshold_Count : in String_Count);
-- Remove from Counter all entries whose count is below the threshold
function Simple_Dictionary
(Counter : in Word_Counter;
Word_Count : in Natural;
Method : in Methods.Enum := Methods.Encoded)
return String_Lists.List;
-- Return the Word_Count words in Counter that have the highest score,
-- the score being count * length.
procedure Simple_Dictionary_And_Pending
(Counter : in Word_Counter;
Word_Count : in Natural;
Selected : out String_Lists.List;
Pending : out String_Lists.List;
Method : in Methods.Enum := Methods.Encoded;
Max_Pending_Count : in Ada.Containers.Count_Type
:= Ada.Containers.Count_Type'Last);
-- Return in Selected the Word_Count words in Counter that have the
-- highest score, and in Pending the remaining words,
-- the score being count * length.
type Dictionary_Counts is
array (Ada.Streams.Stream_Element) of String_Count;
procedure Evaluate_Dictionary
(Dict : in Dictionary;
Corpus : in String_Lists.List;
Compressed_Size : out Ada.Streams.Stream_Element_Count;
Counts : out Dictionary_Counts);
procedure Evaluate_Dictionary_Partial
(Dict : in Dictionary;
Corpus_Entry : in String;
Compressed_Size : in out Ada.Streams.Stream_Element_Count;
Counts : in out Dictionary_Counts);
-- Compress all strings of Corpus, returning the total number of
-- compressed bytes and the number of uses for each dictionary
-- element.
function Worst_Index
(Dict : in Dictionary;
Counts : in Dictionary_Counts;
Method : in Methods.Enum)
return Ada.Streams.Stream_Element;
-- Return the element with worst score
type Score_Value is range 0 .. 2 ** 31 - 1;
function Length
(Dict : in Dictionary;
E : in Ada.Streams.Stream_Element)
return Score_Value
is (Natools.Smaz.Dict_Entry (Dict, E)'Length);
-- Length of a dictionary entry
function Score_Encoded
(Dict : in Dictionary;
Counts : in Natools.Smaz.Tools.Dictionary_Counts;
E : Ada.Streams.Stream_Element)
return Score_Value
is (Score_Value (Counts (E)) * Length (Dict, E));
-- Score value using the amount of encoded data using E
function Score_Frequency
(Dict : in Dictionary;
Counts : in Natools.Smaz.Tools.Dictionary_Counts;
E : Ada.Streams.Stream_Element)
return Score_Value
is (Score_Value (Counts (E)));
-- Score value using the number of times E was used
function Score_Gain
(Dict : in Dictionary;
Counts : in Natools.Smaz.Tools.Dictionary_Counts;
E : Ada.Streams.Stream_Element)
return Score_Value
is (Score_Value (Counts (E)) * (Length (Dict, E) - 1));
-- Score value using the number of bytes saved using E
function Score
(Dict : in Dictionary;
Counts : in Natools.Smaz.Tools.Dictionary_Counts;
E : in Ada.Streams.Stream_Element;
Method : in Methods.Enum)
return Score_Value
is (case Method is
when Methods.Encoded => Score_Encoded (Dict, Counts, E),
when Methods.Frequency => Score_Frequency (Dict, Counts, E),
when Methods.Gain => Score_Gain (Dict, Counts, E));
-- Scare value with dynamically chosen method
private
package Word_Maps is new Ada.Containers.Indefinite_Ordered_Maps
(String, String_Count);
type Word_Counter is record
Map : Word_Maps.Map;
end record;
type Scored_Word (Size : Natural) is record
Word : String (1 .. Size);
Score : Score_Value;
end record;
function "<" (Left, Right : Scored_Word) return Boolean
is (Left.Score > Right.Score
or else (Left.Score = Right.Score and then Left.Word < Right.Word));
function To_Scored_Word
(Cursor : in Word_Maps.Cursor;
Method : in Methods.Enum)
return Scored_Word;
package Scored_Word_Sets is new Ada.Containers.Indefinite_Ordered_Sets
(Scored_Word);
package Dictionary_Maps is new Ada.Containers.Indefinite_Ordered_Maps
(String, Ada.Streams.Stream_Element);
Search_Map : Dictionary_Maps.Map;
type Trie_Node;
type Trie_Node_Access is access Trie_Node;
type Trie_Node_Array is array (Character) of Trie_Node_Access;
type Trie_Node (Is_Leaf : Boolean) is new Ada.Finalization.Controlled
with record
Index : Natural;
case Is_Leaf is
when True => null;
when False => Children : Trie_Node_Array;
end case;
end record;
overriding procedure Adjust (Node : in out Trie_Node);
overriding procedure Finalize (Node : in out Trie_Node);
type Search_Trie is record
Not_Found : Natural;
Root : Trie_Node (False);
end record;
Trie_For_Search : Search_Trie;
end Natools.Smaz.Tools;
|
------------------------------------------------------------------------------
-- Copyright (c) 2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Smaz.Tools helps building and generating dictionary for use --
-- with its parent package. Note that the dictionary is intended to be --
-- generated and hard-coded, so the final client shouldn't need this --
-- package. --
------------------------------------------------------------------------------
with Ada.Containers.Indefinite_Doubly_Linked_Lists;
with Natools.S_Expressions;
private with Ada.Containers.Indefinite_Ordered_Maps;
private with Ada.Containers.Indefinite_Ordered_Sets;
private with Ada.Finalization;
package Natools.Smaz.Tools is
pragma Preelaborate;
package String_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists
(String);
procedure Read_List
(List : out String_Lists.List;
Descriptor : in out S_Expressions.Descriptor'Class);
-- Read atoms from Descriptor to fill List
function To_Dictionary
(List : in String_Lists.List;
Variable_Length_Verbatim : in Boolean)
return Dictionary
with Pre => String_Lists.Length (List) in 1 ..
Ada.Containers.Count_Type (Ada.Streams.Stream_Element'Last);
-- Build a Dictionary object from a string list
-- Note that Hash is set to a placeholder which uncinditionnally
-- raises Program_Error when called.
generic
with procedure Put_Line (Line : String);
procedure Print_Dictionary_In_Ada
(Dict : in Dictionary;
Hash_Image : in String := "TODO";
Max_Width : in Positive := 70;
First_Prefix : in String := " := (";
Prefix : in String := " ";
Half_Indent : in String := " ");
-- Output Ada code corresponding to the value of the dictionary.
-- Note that Prefix is the actual base indentation, while Half_Indent
-- is added beyond Prefix before values continued on another line.
-- Frist_Prefix is used instead of Prefix on the first line.
-- All the defaults value are what was used to generate the constant
-- in Natools.Smaz.Original.
function Remove_Element
(Dict : in Dictionary;
Index : in Ada.Streams.Stream_Element)
return Dictionary
with Pre => Index <= Dict.Dict_Last,
Post => Dict.Dict_Last = Remove_Element'Result.Dict_Last + 1
and then (Index = 0
or else (for all I in 0 .. Index - 1
=> Dict_Entry (Dict, I)
= Dict_Entry (Remove_Element'Result, I)))
and then (Index = Dict.Dict_Last
or else (for all I in Index .. Dict.Dict_Last - 1
=> Dict_Entry (Dict, I + 1)
= Dict_Entry (Remove_Element'Result, I)));
-- Return a new dictionary equal to Dict without element for Index
function Append_String
(Dict : in Dictionary;
Value : in String)
return Dictionary
with Pre => Dict.Dict_Last < Ada.Streams.Stream_Element'Last
and then Value'Length > 0,
Post => Dict.Dict_Last = Append_String'Result.Dict_Last - 1
and then (for all I in 0 .. Dict.Dict_Last
=> Dict_Entry (Dict, I)
= Dict_Entry (Append_String'Result, I))
and then Dict_Entry (Append_String'Result,
Append_String'Result.Dict_Last)
= Value;
-- Return a new dictionary with Value appended
List_For_Linear_Search : String_Lists.List;
function Linear_Search (Value : String) return Natural;
-- Function and data source for inefficient but dynamic function
-- that can be used with Dictionary.Hash.
procedure Set_Dictionary_For_Map_Search (Dict : in Dictionary);
function Map_Search (Value : String) return Natural;
-- Function and data source for logarithmic search using standard
-- ordered map, that can be used with Dictionary.Hash.
type Search_Trie is private;
procedure Initialize (Trie : out Search_Trie; Dict : in Dictionary);
function Search (Trie : in Search_Trie; Value : in String) return Natural;
-- Trie-based search in a dynamic dictionary, for lookup whose
-- speed-vs-memory is even more skewed towards speed.
procedure Set_Dictionary_For_Trie_Search (Dict : in Dictionary);
function Trie_Search (Value : String) return Natural;
-- Function and data source for trie-based search that can be
-- used with Dictionary.Hash.
type String_Count is range 0 .. 2 ** 31 - 1;
-- Type for a number of substring occurrences
package Methods is
type Enum is (Encoded, Frequency, Gain);
end Methods;
-- Evaluation methods to select words to remove or include
type Word_Counter is private;
-- Accumulate frequency/occurrence counts for a set of strings
procedure Add_Word
(Counter : in out Word_Counter;
Word : in String;
Count : in String_Count := 1);
-- Include Count number of occurrences of Word in Counter
procedure Add_Substrings
(Counter : in out Word_Counter;
Phrase : in String;
Min_Size : in Positive;
Max_Size : in Positive);
-- Include all the substrings of Phrase whose lengths are
-- between Min_Size and Max_Size.
procedure Add_Words
(Counter : in out Word_Counter;
Phrase : in String;
Min_Size : in Positive;
Max_Size : in Positive);
-- Add the "words" from Phrase into Counter, with a word being currently
-- defined as anything between ASCII blanks or punctuation,
-- or in other words [0-9A-Za-z\x80-\xFF]+
procedure Filter_By_Count
(Counter : in out Word_Counter;
Threshold_Count : in String_Count);
-- Remove from Counter all entries whose count is below the threshold
function Simple_Dictionary
(Counter : in Word_Counter;
Word_Count : in Natural;
Method : in Methods.Enum := Methods.Encoded)
return String_Lists.List;
-- Return the Word_Count words in Counter that have the highest score,
-- the score being count * length.
procedure Simple_Dictionary_And_Pending
(Counter : in Word_Counter;
Word_Count : in Natural;
Selected : out String_Lists.List;
Pending : out String_Lists.List;
Method : in Methods.Enum := Methods.Encoded;
Max_Pending_Count : in Ada.Containers.Count_Type
:= Ada.Containers.Count_Type'Last);
-- Return in Selected the Word_Count words in Counter that have the
-- highest score, and in Pending the remaining words,
-- the score being count * length.
type Dictionary_Counts is
array (Ada.Streams.Stream_Element) of String_Count;
procedure Evaluate_Dictionary
(Dict : in Dictionary;
Corpus : in String_Lists.List;
Compressed_Size : out Ada.Streams.Stream_Element_Count;
Counts : out Dictionary_Counts);
procedure Evaluate_Dictionary_Partial
(Dict : in Dictionary;
Corpus_Entry : in String;
Compressed_Size : in out Ada.Streams.Stream_Element_Count;
Counts : in out Dictionary_Counts);
-- Compress all strings of Corpus, returning the total number of
-- compressed bytes and the number of uses for each dictionary
-- element.
function Worst_Index
(Dict : in Dictionary;
Counts : in Dictionary_Counts;
Method : in Methods.Enum)
return Ada.Streams.Stream_Element;
-- Return the element with worst score
type Score_Value is range 0 .. 2 ** 31 - 1;
function Score_Encoded
(Count : in String_Count; Length : in Positive) return Score_Value
is (Score_Value (Count) * Score_Value (Length));
-- Score value using the amount of encoded data by the element
function Score_Frequency
(Count : in String_Count; Length : in Positive) return Score_Value
is (Score_Value (Count));
-- Score value using the number of times the element was used
function Score_Gain
(Count : in String_Count; Length : in Positive) return Score_Value
is (Score_Value (Count) * (Score_Value (Length) - 1));
-- Score value using the number of bytes saved using the element
function Score
(Count : in String_Count;
Length : in Positive;
Method : in Methods.Enum)
return Score_Value
is (case Method is
when Methods.Encoded => Score_Encoded (Count, Length),
when Methods.Frequency => Score_Frequency (Count, Length),
when Methods.Gain => Score_Gain (Count, Length));
-- Scare value with dynamically chosen method
function Length
(Dict : in Dictionary;
E : in Ada.Streams.Stream_Element)
return Positive
is (Natools.Smaz.Dict_Entry (Dict, E)'Length);
-- Length of a dictionary entry
function Score_Encoded
(Dict : in Dictionary;
Counts : in Natools.Smaz.Tools.Dictionary_Counts;
E : Ada.Streams.Stream_Element)
return Score_Value
is (Score_Encoded (Counts (E), Length (Dict, E)));
-- Score value using the amount of encoded data using E
function Score_Frequency
(Dict : in Dictionary;
Counts : in Natools.Smaz.Tools.Dictionary_Counts;
E : Ada.Streams.Stream_Element)
return Score_Value
is (Score_Frequency (Counts (E), Length (Dict, E)));
-- Score value using the number of times E was used
function Score_Gain
(Dict : in Dictionary;
Counts : in Natools.Smaz.Tools.Dictionary_Counts;
E : Ada.Streams.Stream_Element)
return Score_Value
is (Score_Gain (Counts (E), Length (Dict, E)));
-- Score value using the number of bytes saved using E
function Score
(Dict : in Dictionary;
Counts : in Natools.Smaz.Tools.Dictionary_Counts;
E : in Ada.Streams.Stream_Element;
Method : in Methods.Enum)
return Score_Value
is (Score (Counts (E), Length (Dict, E), Method));
-- Scare value with dynamically chosen method
private
package Word_Maps is new Ada.Containers.Indefinite_Ordered_Maps
(String, String_Count);
type Word_Counter is record
Map : Word_Maps.Map;
end record;
type Scored_Word (Size : Natural) is record
Word : String (1 .. Size);
Score : Score_Value;
end record;
function "<" (Left, Right : Scored_Word) return Boolean
is (Left.Score > Right.Score
or else (Left.Score = Right.Score and then Left.Word < Right.Word));
function To_Scored_Word
(Cursor : in Word_Maps.Cursor;
Method : in Methods.Enum)
return Scored_Word;
package Scored_Word_Sets is new Ada.Containers.Indefinite_Ordered_Sets
(Scored_Word);
package Dictionary_Maps is new Ada.Containers.Indefinite_Ordered_Maps
(String, Ada.Streams.Stream_Element);
Search_Map : Dictionary_Maps.Map;
type Trie_Node;
type Trie_Node_Access is access Trie_Node;
type Trie_Node_Array is array (Character) of Trie_Node_Access;
type Trie_Node (Is_Leaf : Boolean) is new Ada.Finalization.Controlled
with record
Index : Natural;
case Is_Leaf is
when True => null;
when False => Children : Trie_Node_Array;
end case;
end record;
overriding procedure Adjust (Node : in out Trie_Node);
overriding procedure Finalize (Node : in out Trie_Node);
type Search_Trie is record
Not_Found : Natural;
Root : Trie_Node (False);
end record;
Trie_For_Search : Search_Trie;
end Natools.Smaz.Tools;
|
add dictionary-independent scoring functions
|
smaz-tools: add dictionary-independent scoring functions
|
Ada
|
isc
|
faelys/natools
|
52e169efbfce2431041fd3ec1e70c845cd2a7016
|
src/asf-applications-main.ads
|
src/asf-applications-main.ads
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- 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 Util.Beans.Basic;
with Util.Locales;
with EL.Objects;
with EL.Contexts;
with EL.Functions;
with EL.Functions.Default;
with EL.Expressions;
with EL.Variables.Default;
with Ada.Strings.Unbounded;
with ASF.Locales;
with ASF.Factory;
with ASF.Converters;
with ASF.Validators;
with ASF.Contexts.Faces;
with ASF.Contexts.Exceptions;
with ASF.Lifecycles;
with ASF.Applications.Views;
with ASF.Navigations;
with ASF.Beans;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Events.Faces.Actions;
with Security.Policies; use Security;
with Security.OAuth.Servers;
package ASF.Applications.Main is
use ASF.Beans;
-- ------------------------------
-- Factory for creation of lifecycle, view handler
-- ------------------------------
type Application_Factory is tagged limited private;
-- Create the lifecycle handler. The lifecycle handler is created during
-- the initialization phase of the application. The default implementation
-- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object.
-- It can be overriden to change the behavior of the ASF request lifecycle.
function Create_Lifecycle_Handler (App : in Application_Factory)
return ASF.Lifecycles.Lifecycle_Access;
-- Create the view handler. The view handler is created during
-- the initialization phase of the application. The default implementation
-- creates an <b>ASF.Applications.Views.View_Handler</b> object.
-- It can be overriden to change the views associated with the application.
function Create_View_Handler (App : in Application_Factory)
return ASF.Applications.Views.View_Handler_Access;
-- Create the navigation handler. The navigation handler is created during
-- the initialization phase of the application. The default implementation
-- creates an <b>ASF.Navigations.Navigation_Handler</b> object.
-- It can be overriden to change the navigations associated with the application.
function Create_Navigation_Handler (App : in Application_Factory)
return ASF.Navigations.Navigation_Handler_Access;
-- Create the security policy manager. The security policy manager is created during
-- the initialization phase of the application. The default implementation
-- creates a <b>Security.Policies.Policy_Manager</b> object.
function Create_Security_Manager (App : in Application_Factory)
return Security.Policies.Policy_Manager_Access;
-- Create the OAuth application manager. The OAuth application manager is created
-- during the initialization phase of the application. The default implementation
-- creates a <b>Security.OAuth.Servers.Auth_Manager</b> object.
function Create_OAuth_Manager (App : in Application_Factory)
return Security.OAuth.Servers.Auth_Manager_Access;
-- Create the exception handler. The exception handler is created during
-- the initialization phase of the application. The default implementation
-- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object.
function Create_Exception_Handler (App : in Application_Factory)
return ASF.Contexts.Exceptions.Exception_Handler_Access;
-- ------------------------------
-- Application
-- ------------------------------
type Application is new ASF.Servlets.Servlet_Registry
and ASF.Events.Faces.Actions.Action_Listener with private;
type Application_Access is access all Application'Class;
-- Get the application view handler.
function Get_View_Handler (App : access Application)
return access Views.View_Handler'Class;
-- Get the lifecycle handler.
function Get_Lifecycle_Handler (App : in Application)
return ASF.Lifecycles.Lifecycle_Access;
-- Get the navigation handler.
function Get_Navigation_Handler (App : in Application)
return ASF.Navigations.Navigation_Handler_Access;
-- Get the permission manager associated with this application.
function Get_Security_Manager (App : in Application)
return Security.Policies.Policy_Manager_Access;
-- Get the OAuth application manager associated with this application.
function Get_OAuth_Manager (App : in Application)
return Security.OAuth.Servers.Auth_Manager_Access;
-- Get the action event listener responsible for processing action
-- events and triggering the navigation to the next view using the
-- navigation handler.
function Get_Action_Listener (App : in Application)
return ASF.Events.Faces.Actions.Action_Listener_Access;
-- Process the action associated with the action event. The action returns
-- and outcome which is then passed to the navigation handler to navigate to
-- the next view.
overriding
procedure Process_Action (Listener : in Application;
Event : in ASF.Events.Faces.Actions.Action_Event'Class;
Context : in out Contexts.Faces.Faces_Context'Class);
-- Execute the action method. The action returns and outcome which is then passed
-- to the navigation handler to navigate to the next view.
procedure Process_Action (Listener : in Application;
Method : in EL.Expressions.Method_Info;
Context : in out Contexts.Faces.Faces_Context'Class);
-- Initialize the application
procedure Initialize (App : in out Application;
Conf : in Config;
Factory : in out Application_Factory'Class);
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
procedure Initialize_Components (App : in out Application);
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
procedure Initialize_Config (App : in out Application;
Conf : in out Config);
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
procedure Initialize_Servlets (App : in out Application);
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
procedure Initialize_Filters (App : in out Application);
-- Finalizes the application, freeing the memory.
overriding
procedure Finalize (App : in out Application);
-- Get the configuration parameter;
function Get_Config (App : Application;
Param : Config_Param) return String;
-- Set a global variable in the global EL contexts.
procedure Set_Global (App : in out Application;
Name : in String;
Value : in String);
procedure Set_Global (App : in out Application;
Name : in String;
Value : in EL.Objects.Object);
-- Resolve a global variable and return its value.
-- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist.
function Get_Global (App : in Application;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Context : in EL.Contexts.ELContext'Class)
return EL.Objects.Object;
-- Get the list of supported locales for this application.
function Get_Supported_Locales (App : in Application)
return Util.Locales.Locale_Array;
-- Add the locale to the list of supported locales.
procedure Add_Supported_Locale (App : in out Application;
Locale : in Util.Locales.Locale);
-- Get the default locale defined by the application.
function Get_Default_Locale (App : in Application) return Util.Locales.Locale;
-- Set the default locale defined by the application.
procedure Set_Default_Locale (App : in out Application;
Locale : in Util.Locales.Locale);
-- Compute the locale that must be used according to the <b>Accept-Language</b> request
-- header and the application supported locales.
function Calculate_Locale (Handler : in Application;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Util.Locales.Locale;
-- Register a bundle and bind it to a facelet variable.
procedure Register (App : in out Application;
Name : in String;
Bundle : in String);
-- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>.
-- The class must have been registered by using the <b>Register</b> class operation.
-- The scope defines the scope of the bean.
procedure Register (App : in out Application;
Name : in String;
Class : in String;
Params : in Parameter_Bean_Ref.Ref;
Scope : in Scope_Type := REQUEST_SCOPE);
-- Register under the name identified by <b>Name</b> the class instance <b>Class</b>.
procedure Register_Class (App : in out Application;
Name : in String;
Class : in ASF.Beans.Class_Binding_Access);
-- Register under the name identified by <b>Name</b> a function to create a bean.
-- This is a simplified class registration.
procedure Register_Class (App : in out Application;
Name : in String;
Handler : in ASF.Beans.Create_Bean_Access);
-- Create a bean by using the create operation registered for the name
procedure Create (App : in Application;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Context : in EL.Contexts.ELContext'Class;
Result : out Util.Beans.Basic.Readonly_Bean_Access;
Scope : out Scope_Type);
-- Add a converter in the application. The converter is referenced by
-- the specified name in the XHTML files.
procedure Add_Converter (App : in out Application;
Name : in String;
Converter : in ASF.Converters.Converter_Access);
-- Register a binding library in the factory.
procedure Add_Components (App : in out Application;
Bindings : in ASF.Factory.Factory_Bindings_Access);
-- Closes the application
procedure Close (App : in out Application);
-- Set the current faces context before processing a view.
procedure Set_Context (App : in out Application;
Context : in ASF.Contexts.Faces.Faces_Context_Access);
-- Execute the lifecycle phases on the faces context.
procedure Execute_Lifecycle (App : in Application;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Dispatch the request received on a page.
procedure Dispatch (App : in out Application;
Page : in String;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Dispatch a bean action request.
-- 1. Find the bean object identified by <b>Name</b>, create it if necessary.
-- 2. Resolve the bean method identified by <b>Operation</b>.
-- 3. If the method is an action method (see ASF.Events.Actions), call that method.
-- 4. Using the outcome action result, decide using the navigation handler what
-- is the result view.
-- 5. Render the result view resolved by the navigation handler.
procedure Dispatch (App : in out Application;
Name : in String;
Operation : in String;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class));
-- Find the converter instance that was registered under the given name.
-- Returns null if no such converter exist.
function Find (App : in Application;
Name : in EL.Objects.Object) return ASF.Converters.Converter_Access;
-- Find the validator instance that was registered under the given name.
-- Returns null if no such validator exist.
function Find_Validator (App : in Application;
Name : in EL.Objects.Object)
return ASF.Validators.Validator_Access;
-- Register some functions
generic
with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
procedure Register_Functions (App : in out Application'Class);
-- Register some bean definitions.
generic
with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory);
procedure Register_Beans (App : in out Application'Class);
-- Load the resource bundle identified by the <b>Name</b> and for the given
-- <b>Locale</b>.
procedure Load_Bundle (App : in out Application;
Name : in String;
Locale : in String;
Bundle : out ASF.Locales.Bundle);
private
type Application_Factory is tagged limited null record;
type Application is new ASF.Servlets.Servlet_Registry
and ASF.Events.Faces.Actions.Action_Listener with record
View : aliased ASF.Applications.Views.View_Handler;
Lifecycle : ASF.Lifecycles.Lifecycle_Access;
Factory : aliased ASF.Beans.Bean_Factory;
Locales : ASF.Locales.Factory;
Globals : aliased EL.Variables.Default.Default_Variable_Mapper;
Functions : aliased EL.Functions.Default.Default_Function_Mapper;
-- The component factory
Components : aliased ASF.Factory.Component_Factory;
-- The action listener.
Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access;
-- The navigation handler.
Navigation : ASF.Navigations.Navigation_Handler_Access;
-- The permission manager.
Permissions : Security.Policies.Policy_Manager_Access;
-- The OAuth application manager.
OAuth : Security.OAuth.Servers.Auth_Manager_Access;
-- Exception handler
Exceptions : ASF.Contexts.Exceptions.Exception_Handler_Access;
end record;
end ASF.Applications.Main;
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- 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 Util.Beans.Basic;
with Util.Locales;
with EL.Objects;
with EL.Contexts;
with EL.Functions;
with EL.Functions.Default;
with EL.Expressions;
with EL.Variables.Default;
with Ada.Strings.Unbounded;
with ASF.Locales;
with ASF.Factory;
with ASF.Converters;
with ASF.Validators;
with ASF.Contexts.Faces;
with ASF.Contexts.Exceptions;
with ASF.Lifecycles;
with ASF.Applications.Views;
with ASF.Navigations;
with ASF.Beans;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Events.Faces.Actions;
with Security.Policies; use Security;
with Security.OAuth.Servers;
package ASF.Applications.Main is
use ASF.Beans;
-- ------------------------------
-- Factory for creation of lifecycle, view handler
-- ------------------------------
type Application_Factory is tagged limited private;
-- Create the lifecycle handler. The lifecycle handler is created during
-- the initialization phase of the application. The default implementation
-- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object.
-- It can be overriden to change the behavior of the ASF request lifecycle.
function Create_Lifecycle_Handler (App : in Application_Factory)
return ASF.Lifecycles.Lifecycle_Access;
-- Create the view handler. The view handler is created during
-- the initialization phase of the application. The default implementation
-- creates an <b>ASF.Applications.Views.View_Handler</b> object.
-- It can be overriden to change the views associated with the application.
function Create_View_Handler (App : in Application_Factory)
return ASF.Applications.Views.View_Handler_Access;
-- Create the navigation handler. The navigation handler is created during
-- the initialization phase of the application. The default implementation
-- creates an <b>ASF.Navigations.Navigation_Handler</b> object.
-- It can be overriden to change the navigations associated with the application.
function Create_Navigation_Handler (App : in Application_Factory)
return ASF.Navigations.Navigation_Handler_Access;
-- Create the security policy manager. The security policy manager is created during
-- the initialization phase of the application. The default implementation
-- creates a <b>Security.Policies.Policy_Manager</b> object.
function Create_Security_Manager (App : in Application_Factory)
return Security.Policies.Policy_Manager_Access;
-- Create the OAuth application manager. The OAuth application manager is created
-- during the initialization phase of the application. The default implementation
-- creates a <b>Security.OAuth.Servers.Auth_Manager</b> object.
function Create_OAuth_Manager (App : in Application_Factory)
return Security.OAuth.Servers.Auth_Manager_Access;
-- Create the exception handler. The exception handler is created during
-- the initialization phase of the application. The default implementation
-- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object.
function Create_Exception_Handler (App : in Application_Factory)
return ASF.Contexts.Exceptions.Exception_Handler_Access;
-- ------------------------------
-- Application
-- ------------------------------
type Application is new ASF.Servlets.Servlet_Registry
and ASF.Events.Faces.Actions.Action_Listener with private;
type Application_Access is access all Application'Class;
-- Get the application view handler.
function Get_View_Handler (App : access Application)
return access Views.View_Handler'Class;
-- Get the lifecycle handler.
function Get_Lifecycle_Handler (App : in Application)
return ASF.Lifecycles.Lifecycle_Access;
-- Get the navigation handler.
function Get_Navigation_Handler (App : in Application)
return ASF.Navigations.Navigation_Handler_Access;
-- Get the permission manager associated with this application.
function Get_Security_Manager (App : in Application)
return Security.Policies.Policy_Manager_Access;
-- Get the OAuth application manager associated with this application.
function Get_OAuth_Manager (App : in Application)
return Security.OAuth.Servers.Auth_Manager_Access;
-- Get the action event listener responsible for processing action
-- events and triggering the navigation to the next view using the
-- navigation handler.
function Get_Action_Listener (App : in Application)
return ASF.Events.Faces.Actions.Action_Listener_Access;
-- Get the exception handler configured for this application.
function Get_Exception_Handler (App : in Application)
return ASF.Contexts.Exceptions.Exception_Handler_Access;
-- Process the action associated with the action event. The action returns
-- and outcome which is then passed to the navigation handler to navigate to
-- the next view.
overriding
procedure Process_Action (Listener : in Application;
Event : in ASF.Events.Faces.Actions.Action_Event'Class;
Context : in out Contexts.Faces.Faces_Context'Class);
-- Execute the action method. The action returns and outcome which is then passed
-- to the navigation handler to navigate to the next view.
procedure Process_Action (Listener : in Application;
Method : in EL.Expressions.Method_Info;
Context : in out Contexts.Faces.Faces_Context'Class);
-- Initialize the application
procedure Initialize (App : in out Application;
Conf : in Config;
Factory : in out Application_Factory'Class);
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
procedure Initialize_Components (App : in out Application);
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
procedure Initialize_Config (App : in out Application;
Conf : in out Config);
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
procedure Initialize_Servlets (App : in out Application);
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
procedure Initialize_Filters (App : in out Application);
-- Finalizes the application, freeing the memory.
overriding
procedure Finalize (App : in out Application);
-- Get the configuration parameter;
function Get_Config (App : Application;
Param : Config_Param) return String;
-- Set a global variable in the global EL contexts.
procedure Set_Global (App : in out Application;
Name : in String;
Value : in String);
procedure Set_Global (App : in out Application;
Name : in String;
Value : in EL.Objects.Object);
-- Resolve a global variable and return its value.
-- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist.
function Get_Global (App : in Application;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Context : in EL.Contexts.ELContext'Class)
return EL.Objects.Object;
-- Get the list of supported locales for this application.
function Get_Supported_Locales (App : in Application)
return Util.Locales.Locale_Array;
-- Add the locale to the list of supported locales.
procedure Add_Supported_Locale (App : in out Application;
Locale : in Util.Locales.Locale);
-- Get the default locale defined by the application.
function Get_Default_Locale (App : in Application) return Util.Locales.Locale;
-- Set the default locale defined by the application.
procedure Set_Default_Locale (App : in out Application;
Locale : in Util.Locales.Locale);
-- Compute the locale that must be used according to the <b>Accept-Language</b> request
-- header and the application supported locales.
function Calculate_Locale (Handler : in Application;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Util.Locales.Locale;
-- Register a bundle and bind it to a facelet variable.
procedure Register (App : in out Application;
Name : in String;
Bundle : in String);
-- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>.
-- The class must have been registered by using the <b>Register</b> class operation.
-- The scope defines the scope of the bean.
procedure Register (App : in out Application;
Name : in String;
Class : in String;
Params : in Parameter_Bean_Ref.Ref;
Scope : in Scope_Type := REQUEST_SCOPE);
-- Register under the name identified by <b>Name</b> the class instance <b>Class</b>.
procedure Register_Class (App : in out Application;
Name : in String;
Class : in ASF.Beans.Class_Binding_Access);
-- Register under the name identified by <b>Name</b> a function to create a bean.
-- This is a simplified class registration.
procedure Register_Class (App : in out Application;
Name : in String;
Handler : in ASF.Beans.Create_Bean_Access);
-- Create a bean by using the create operation registered for the name
procedure Create (App : in Application;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Context : in EL.Contexts.ELContext'Class;
Result : out Util.Beans.Basic.Readonly_Bean_Access;
Scope : out Scope_Type);
-- Add a converter in the application. The converter is referenced by
-- the specified name in the XHTML files.
procedure Add_Converter (App : in out Application;
Name : in String;
Converter : in ASF.Converters.Converter_Access);
-- Register a binding library in the factory.
procedure Add_Components (App : in out Application;
Bindings : in ASF.Factory.Factory_Bindings_Access);
-- Closes the application
procedure Close (App : in out Application);
-- Set the current faces context before processing a view.
procedure Set_Context (App : in out Application;
Context : in ASF.Contexts.Faces.Faces_Context_Access);
-- Execute the lifecycle phases on the faces context.
procedure Execute_Lifecycle (App : in Application;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Dispatch the request received on a page.
procedure Dispatch (App : in out Application;
Page : in String;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Dispatch a bean action request.
-- 1. Find the bean object identified by <b>Name</b>, create it if necessary.
-- 2. Resolve the bean method identified by <b>Operation</b>.
-- 3. If the method is an action method (see ASF.Events.Actions), call that method.
-- 4. Using the outcome action result, decide using the navigation handler what
-- is the result view.
-- 5. Render the result view resolved by the navigation handler.
procedure Dispatch (App : in out Application;
Name : in String;
Operation : in String;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class));
-- Find the converter instance that was registered under the given name.
-- Returns null if no such converter exist.
function Find (App : in Application;
Name : in EL.Objects.Object) return ASF.Converters.Converter_Access;
-- Find the validator instance that was registered under the given name.
-- Returns null if no such validator exist.
function Find_Validator (App : in Application;
Name : in EL.Objects.Object)
return ASF.Validators.Validator_Access;
-- Register some functions
generic
with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
procedure Register_Functions (App : in out Application'Class);
-- Register some bean definitions.
generic
with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory);
procedure Register_Beans (App : in out Application'Class);
-- Load the resource bundle identified by the <b>Name</b> and for the given
-- <b>Locale</b>.
procedure Load_Bundle (App : in out Application;
Name : in String;
Locale : in String;
Bundle : out ASF.Locales.Bundle);
private
type Application_Factory is tagged limited null record;
type Application is new ASF.Servlets.Servlet_Registry
and ASF.Events.Faces.Actions.Action_Listener with record
View : aliased ASF.Applications.Views.View_Handler;
Lifecycle : ASF.Lifecycles.Lifecycle_Access;
Factory : aliased ASF.Beans.Bean_Factory;
Locales : ASF.Locales.Factory;
Globals : aliased EL.Variables.Default.Default_Variable_Mapper;
Functions : aliased EL.Functions.Default.Default_Function_Mapper;
-- The component factory
Components : aliased ASF.Factory.Component_Factory;
-- The action listener.
Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access;
-- The navigation handler.
Navigation : ASF.Navigations.Navigation_Handler_Access;
-- The permission manager.
Permissions : Security.Policies.Policy_Manager_Access;
-- The OAuth application manager.
OAuth : Security.OAuth.Servers.Auth_Manager_Access;
-- Exception handler
Exceptions : ASF.Contexts.Exceptions.Exception_Handler_Access;
end record;
end ASF.Applications.Main;
|
Declare the Get_Exception_Handler function
|
Declare the Get_Exception_Handler function
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
1675d4fd3e2e89bfadff5dc40e99edaedd36b52b
|
t0026.adb
|
t0026.adb
|
-- t0026.adb - Sat Jan 11 23:18:41 2014
--
-- (c) Warren W. Gay VE3WWG [email protected]
--
-- Protected under the following license:
-- GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999
with Ada.Text_IO;
with Posix;
use Posix;
procedure T0026 is
use Ada.Text_IO;
Child : pid_t := -1;
Resource : s_rusage;
Status : int_t := 0;
Error : errno_t;
pragma Volatile(Error);
begin
Put_Line("Test 0026 - Wait3");
Fork(Child,Error);
pragma Assert(Error = 0);
if Child = 0 then
-- Child fork
for Count in Natural(0)..10000000 loop
Error := 0;
end loop;
Sys_Exit(42);
end if;
Wait3(Child,0,Status,Resource,Error);
pragma Assert(Error = 0);
pragma Assert(WIFEXITED(Status));
pragma Assert(WEXITSTATUS(Status) = 42);
pragma Assert(Resource.ru_utime.tv_usec > 0);
pragma Assert(Resource.ru_stime.tv_usec > 0);
Put_Line("Test 0026 Passed.");
end T0026;
|
-- t0026.adb - Sat Jan 11 23:18:41 2014
--
-- (c) Warren W. Gay VE3WWG [email protected]
--
-- Protected under the following license:
-- GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999
with Ada.Text_IO;
with Posix;
use Posix;
procedure T0026 is
use Ada.Text_IO;
Child : pid_t := -1;
Resource : s_rusage;
Status : int_t := 0;
Error : errno_t;
pragma Volatile(Error);
begin
Put_Line("Test 0026 - Wait3");
Fork(Child,Error);
pragma Assert(Error = 0);
if Child = 0 then
-- Child fork
for Count in Natural(0)..10000000 loop
Error := 0;
end loop;
Sys_Exit(42);
end if;
Wait3(Child,0,Status,Resource,Error);
pragma Assert(Error = 0);
pragma Assert(WIFEXITED(Status));
pragma Assert(WEXITSTATUS(Status) = 42);
pragma Assert(Resource.ru_utime.tv_usec > 0);
pragma Assert(Resource.ru_stime.tv_usec >= 0);
Put_Line("Test 0026 Passed.");
end T0026;
|
Fix applied for Linux resource usage
|
Fix applied for Linux resource usage
|
Ada
|
lgpl-2.1
|
ve3wwg/adafpx,ve3wwg/adafpx
|
16d3e388065c3b8d5d53a8ac64db149787f9f6fd
|
src/security-oauth-jwt.adb
|
src/security-oauth-jwt.adb
|
-----------------------------------------------------------------------
-- security-oauth-jwt -- OAuth Java Web Token
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar.Conversions;
with Interfaces.C;
with Util.Encoders;
with Util.Strings;
with Util.Serialize.IO;
with Util.Properties.JSON;
with Util.Log.Loggers;
package body Security.OAuth.JWT is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.JWT");
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time;
-- Decode the part using base64url and parse the JSON content into the property manager.
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String);
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time is
Value : constant String := From.Get (Name);
begin
return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (Value));
end Get_Time;
-- ------------------------------
-- Get the issuer claim from the token (the "iss" claim).
-- ------------------------------
function Get_Issuer (From : in Token) return String is
begin
return From.Claims.Get ("iss");
end Get_Issuer;
-- ------------------------------
-- Get the subject claim from the token (the "sub" claim).
-- ------------------------------
function Get_Subject (From : in Token) return String is
begin
return From.Claims.Get ("sub");
end Get_Subject;
-- ------------------------------
-- Get the audience claim from the token (the "aud" claim).
-- ------------------------------
function Get_Audience (From : in Token) return String is
begin
return From.Claims.Get ("aud");
end Get_Audience;
-- ------------------------------
-- Get the expiration claim from the token (the "exp" claim).
-- ------------------------------
function Get_Expiration (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "exp");
end Get_Expiration;
-- ------------------------------
-- Get the not before claim from the token (the "nbf" claim).
-- ------------------------------
function Get_Not_Before (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "nbf");
end Get_Not_Before;
-- ------------------------------
-- Get the issued at claim from the token (the "iat" claim).
-- ------------------------------
function Get_Issued_At (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "iat");
end Get_Issued_At;
-- ------------------------------
-- Get the authentication time claim from the token (the "auth_time" claim).
-- ------------------------------
function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "auth_time");
end Get_Authentication_Time;
-- ------------------------------
-- Get the JWT ID claim from the token (the "jti" claim).
-- ------------------------------
function Get_JWT_ID (From : in Token) return String is
begin
return From.Claims.Get ("jti");
end Get_JWT_ID;
-- ------------------------------
-- Get the authorized clients claim from the token (the "azp" claim).
-- ------------------------------
function Get_Authorized_Presenters (From : in Token) return String is
begin
return From.Claims.Get ("azp");
end Get_Authorized_Presenters;
-- ------------------------------
-- Get the claim with the given name from the token.
-- ------------------------------
function Get_Claim (From : in Token;
Name : in String) return String is
begin
return From.Claims.Get (Name);
end Get_Claim;
-- ------------------------------
-- Decode the part using base64url and parse the JSON content into the property manager.
-- ------------------------------
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String) is
Decoder : constant Util.Encoders.Encoder := Util.Encoders.Create (Util.Encoders.BASE_64_URL);
Content : constant String := Decoder.Decode (Data);
begin
Log.Debug ("Decoding {0}: {1}", Name, Content);
Util.Properties.JSON.Parse_JSON (Into, Content);
end Decode_Part;
-- ------------------------------
-- Decode a string representing an encoded JWT token according to the JWT specification:
--
-- Section 7. Rules for Creating and Validating a JWT
--
-- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' .
-- The first part represents the header, the second part the claims and the last part
-- the signature. The <tt>Decode</tt> operation splits the parts, decodes them,
-- parses the JSON content represented by the header and the claims.
-- The <tt>Decode</tt> operation does not verify the signature (yet!).
--
-- Return the decoded token or raise an exception.
-- ------------------------------
function Decode (Content : in String) return Token is
Pos1 : constant Natural := Util.Strings.Index (Content, '.');
Pos2 : Natural;
Result : Token;
begin
if Pos1 = 0 then
Log.Error ("Invalid JWT token: missing '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing header separator";
end if;
Pos2 := Util.Strings.Index (Content, '.', Pos1 + 1);
if Pos2 = 0 then
Log.Error ("Invalid JWT token: missing second '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing signature separator";
end if;
Decode_Part (Result.Header, "header", Content (Content'First .. Pos1 - 1));
Decode_Part (Result.Claims, "claims", Content (Pos1 + 1 .. Pos2 - 1));
return Result;
exception
when Util.Serialize.IO.Parse_Error =>
raise Invalid_Token with "Invalid JSON content";
end Decode;
end Security.OAuth.JWT;
|
-----------------------------------------------------------------------
-- security-oauth-jwt -- OAuth Java Web Token
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar.Conversions;
with Interfaces.C;
with Util.Encoders;
with Util.Strings;
with Util.Serialize.IO;
with Util.Properties.JSON;
with Util.Log.Loggers;
package body Security.OAuth.JWT is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.JWT");
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time;
-- Decode the part using base64url and parse the JSON content into the property manager.
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String);
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time is
Value : constant String := From.Get (Name);
begin
return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (Value));
end Get_Time;
-- ------------------------------
-- Get the issuer claim from the token (the "iss" claim).
-- ------------------------------
function Get_Issuer (From : in Token) return String is
begin
return From.Claims.Get ("iss");
end Get_Issuer;
-- ------------------------------
-- Get the subject claim from the token (the "sub" claim).
-- ------------------------------
function Get_Subject (From : in Token) return String is
begin
return From.Claims.Get ("sub");
end Get_Subject;
-- ------------------------------
-- Get the audience claim from the token (the "aud" claim).
-- ------------------------------
function Get_Audience (From : in Token) return String is
begin
return From.Claims.Get ("aud");
end Get_Audience;
-- ------------------------------
-- Get the expiration claim from the token (the "exp" claim).
-- ------------------------------
function Get_Expiration (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "exp");
end Get_Expiration;
-- ------------------------------
-- Get the not before claim from the token (the "nbf" claim).
-- ------------------------------
function Get_Not_Before (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "nbf");
end Get_Not_Before;
-- ------------------------------
-- Get the issued at claim from the token (the "iat" claim).
-- ------------------------------
function Get_Issued_At (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "iat");
end Get_Issued_At;
-- ------------------------------
-- Get the authentication time claim from the token (the "auth_time" claim).
-- ------------------------------
function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "auth_time");
end Get_Authentication_Time;
-- ------------------------------
-- Get the JWT ID claim from the token (the "jti" claim).
-- ------------------------------
function Get_JWT_ID (From : in Token) return String is
begin
return From.Claims.Get ("jti");
end Get_JWT_ID;
-- ------------------------------
-- Get the authorized clients claim from the token (the "azp" claim).
-- ------------------------------
function Get_Authorized_Presenters (From : in Token) return String is
begin
return From.Claims.Get ("azp");
end Get_Authorized_Presenters;
-- ------------------------------
-- Get the claim with the given name from the token.
-- ------------------------------
function Get_Claim (From : in Token;
Name : in String;
Default : in String := "") return String is
begin
return From.Claims.Get (Name, Default);
end Get_Claim;
-- ------------------------------
-- Decode the part using base64url and parse the JSON content into the property manager.
-- ------------------------------
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String) is
Decoder : constant Util.Encoders.Encoder := Util.Encoders.Create (Util.Encoders.BASE_64_URL);
Content : constant String := Decoder.Decode (Data);
begin
Log.Debug ("Decoding {0}: {1}", Name, Content);
Util.Properties.JSON.Parse_JSON (Into, Content);
end Decode_Part;
-- ------------------------------
-- Decode a string representing an encoded JWT token according to the JWT specification:
--
-- Section 7. Rules for Creating and Validating a JWT
--
-- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' .
-- The first part represents the header, the second part the claims and the last part
-- the signature. The <tt>Decode</tt> operation splits the parts, decodes them,
-- parses the JSON content represented by the header and the claims.
-- The <tt>Decode</tt> operation does not verify the signature (yet!).
--
-- Return the decoded token or raise an exception.
-- ------------------------------
function Decode (Content : in String) return Token is
Pos1 : constant Natural := Util.Strings.Index (Content, '.');
Pos2 : Natural;
Result : Token;
begin
if Pos1 = 0 then
Log.Error ("Invalid JWT token: missing '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing header separator";
end if;
Pos2 := Util.Strings.Index (Content, '.', Pos1 + 1);
if Pos2 = 0 then
Log.Error ("Invalid JWT token: missing second '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing signature separator";
end if;
Decode_Part (Result.Header, "header", Content (Content'First .. Pos1 - 1));
Decode_Part (Result.Claims, "claims", Content (Pos1 + 1 .. Pos2 - 1));
return Result;
exception
when Util.Serialize.IO.Parse_Error =>
raise Invalid_Token with "Invalid JSON content";
end Decode;
end Security.OAuth.JWT;
|
Update Get_Claim to have a default value
|
Update Get_Claim to have a default value
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
7659c30ed4aa360e4a1d56915a3c3820dc6c1caa
|
src/util-properties.adb
|
src/util-properties.adb
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties.Factories;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded.Text_IO;
with Interfaces.C.Strings;
package body Util.Properties is
use Ada.Text_IO;
use Ada.Strings.Unbounded.Text_IO;
use Interface_P;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- 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.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
null;
end Set_Value;
function Exists (Self : in Manager'Class;
Name : in String) return Boolean is
begin
-- There is not yet an implementation, no property
if Self.Impl = null then
return False;
end if;
return Exists (Self.Impl.all, +Name);
end Exists;
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean is
begin
-- There is not yet an implementation, no property
if Self.Impl = null then
return False;
end if;
return Exists (Self.Impl.all, Name);
end Exists;
function Get (Self : in Manager'Class;
Name : in String) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return Get (Self.Impl.all, +Name);
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & To_String (Name) & "'";
end if;
return Get (Self.Impl.all, Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return -Get (Self.Impl.all, +Name);
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
return -Get (Self.Impl.all, Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String is
Prop_Name : constant Value := +Name;
begin
if Exists (Self, Prop_Name) then
return Get (Self, Prop_Name);
else
return Default;
end if;
end Get;
procedure Check_And_Create_Impl (Self : in out Manager) is
begin
if Self.Impl = null then
Util.Properties.Factories.Initialize (Self);
elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then
declare
Old : Interface_P.Manager_Access := Self.Impl;
Is_Zero : Boolean;
begin
Self.Impl := Create_Copy (Self.Impl.all);
Util.Concurrent.Counters.Increment (Self.Impl.Count);
Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero);
if Is_Zero then
Delete (Old.all, Old);
end if;
end;
end if;
end Check_And_Create_Impl;
procedure Insert (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Check_And_Create_Impl (Self);
Insert (Self.Impl.all, +Name, +Item);
end Insert;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, +Name, +Item);
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, +Name, Item);
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value) is
begin
Check_And_Create_Impl (Self);
Set (Self.Impl.all, Name, Item);
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in String) is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
Check_And_Create_Impl (Self);
Remove (Self.Impl.all, +Name);
end Remove;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in Value) is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
Check_And_Create_Impl (Self);
Remove (Self.Impl.all, Name);
end Remove;
-- ------------------------------
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
-- ------------------------------
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value)) is
begin
if Self.Impl /= null then
Self.Impl.Iterate (Process);
end if;
end Iterate;
-- ------------------------------
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
-- ------------------------------
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array is
begin
if Self.Impl = null then
declare
Empty : Name_Array (1 .. 0);
begin
return Empty;
end;
else
return Get_Names (Self.Impl.all, Prefix);
end if;
end Get_Names;
procedure Adjust (Object : in out Manager) is
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end if;
end Adjust;
procedure Finalize (Object : in out Manager) is
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero);
if Is_Zero then
Delete (Object.Impl.all, Object.Impl);
end if;
end if;
end Finalize;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access) is
begin
if Self.Impl = null then
Self.Impl := Impl;
-- Self.Impl.Count := 1;
end if;
end Set_Property_Implementation;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
pragma Unreferenced (Strip);
Line : Unbounded_String;
Pos : Natural;
Len : Natural;
begin
while not End_Of_File (File) loop
Line := Get_Line (File);
Len := Length (Line);
if Len /= 0 and then Element (Line, 1) /= '#' then
Pos := Index (Line, "=");
if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then
Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
elsif Pos > 0 and Prefix'Length = 0 then
Name := Head (Line, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
end if;
end if;
end loop;
Name := Null_Unbounded_String;
Value := Null_Unbounded_String;
end Load_Property;
procedure Load_Properties (Self : in out Manager'Class;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
Name, Value : Unbounded_String;
begin
loop
Load_Property (Name, Value, File, Prefix, Strip);
exit when Name = Null_Unbounded_String;
Set (Self, Name, Value);
end loop;
exception
when End_Error =>
return;
end Load_Properties;
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False) is
F : File_Type;
begin
Open (F, In_File, Path);
Load_Properties (Self, F, Prefix, Strip);
Close (F);
end Load_Properties;
-- ------------------------------
-- Save the properties in the given file path.
-- ------------------------------
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "") is
procedure Save_Property (Name, Item : in Value);
Tmp : constant String := Path & ".tmp";
F : File_Type;
procedure Save_Property (Name, Item : in Value) is
begin
Put (F, Name);
Put (F, "=");
Put (F, Item);
New_Line (F);
end Save_Property;
-- Rename a file (the Ada.Directories.Rename does not allow to use the Unix atomic file rename!)
function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr;
Newpath : in Interfaces.C.Strings.chars_ptr) return Integer;
pragma Import (C, Sys_Rename, "rename");
Old_Path : Interfaces.C.Strings.chars_ptr;
New_Path : Interfaces.C.Strings.chars_ptr;
Result : Integer;
begin
Create (File => F, Name => Tmp);
Self.Iterate (Save_Property'Access);
Close (File => F);
-- Do a system atomic rename of old file in the new file.
-- Ada.Directories.Rename does not allow this.
Old_Path := Interfaces.C.Strings.New_String (Tmp);
New_Path := Interfaces.C.Strings.New_String (Path);
Result := Sys_Rename (Old_Path, New_Path);
Interfaces.C.Strings.Free (Old_Path);
Interfaces.C.Strings.Free (New_Path);
if Result /= 0 then
raise Ada.IO_Exceptions.Use_Error with "Cannot rename file";
end if;
end Save_Properties;
-- ------------------------------
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- ------------------------------
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False) is
Names : constant Name_Array := From.Get_Names;
begin
for I in Names'Range loop
declare
Name : Unbounded_String renames Names (I);
begin
if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then
if Strip and Prefix'Length > 0 then
declare
S : constant String := Slice (Name, Prefix'Length + 1, Length (Name));
begin
Self.Set (+(S), From.Get (Name));
end;
else
Self.Set (Name, From.Get (Name));
end if;
end if;
end;
end loop;
end Copy;
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2014, 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.Factories;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded.Text_IO;
with Interfaces.C.Strings;
with Ada.Unchecked_Deallocation;
package body Util.Properties is
use Ada.Text_IO;
use Ada.Strings.Unbounded.Text_IO;
use Interface_P;
use Util.Beans.Objects;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Interface_P.Manager'Class,
Name => Interface_P.Manager_Access);
type Property_Map is new Interface_P.Manager with record
Props : Util.Beans.Objects.Maps.Map_Bean;
end record;
type Property_Map_Access is access all Property_Map;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Property_Map;
Name : in String) return Util.Beans.Objects.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.
overriding
procedure Set_Value (From : in out Property_Map;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
overriding
function Exists (Self : in Property_Map;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Property_Map; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Property_Map;
Process : access procedure (Name, Item : Value));
-- Deep copy of properties stored in 'From' to 'To'.
overriding
function Create_Copy (Self : in Property_Map)
return Interface_P.Manager_Access;
overriding
function Get_Names (Self : in Property_Map;
Prefix : in String) return Name_Array;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Property_Map;
Name : in String) return Util.Beans.Objects.Object is
begin
return From.Props.Get_Value (Name);
end Get_Value;
-- ------------------------------
-- 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.
-- ------------------------------
overriding
procedure Set_Value (From : in out Property_Map;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
From.Props.Set_Value (Name, Value);
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
overriding
function Exists (Self : in Property_Map;
Name : in String)
return Boolean is
begin
return Self.Props.Contains (Name);
end Exists;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
overriding
procedure Remove (Self : in out Property_Map; Name : in Value) is
begin
null;
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Property_Map;
Process : access procedure (Name, Item : Value)) is
begin
null;
end Iterate;
-- Deep copy of properties stored in 'From' to 'To'.
overriding
function Create_Copy (Self : in Property_Map)
return Interface_P.Manager_Access is
Result : Property_Map_Access := new Property_Map;
begin
Result.Props := Self.Props;
return Result.all'Access;
end Create_Copy;
overriding
function Get_Names (Self : in Property_Map;
Prefix : in String) return Name_Array is
N : Name_Array (1 .. 0);
begin
return N;
end Get_Names;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Impl = null then
return Util.Beans.Objects.Null_Object;
else
return From.Impl.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- 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.
-- ------------------------------
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Check_And_Create_Impl (From);
From.Impl.Set_Value (Name, Value);
end Set_Value;
function Exists (Self : in Manager'Class;
Name : in String) return Boolean is
begin
-- There is not yet an implementation, no property
return Self.Impl /= null and then Self.Impl.Exists (Name);
end Exists;
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean is
begin
-- There is not yet an implementation, no property
return Self.Impl /= null and then Self.Impl.Exists (-Name);
end Exists;
function Get (Self : in Manager'Class;
Name : in String) return Value is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return Value (To_Unbounded_String (Self.Impl.Get_Value (Name)));
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return Value is
begin
return Self.Get (-Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return To_String (Self.Impl.Get_Value (Name));
end Get;
function Get (Self : in Manager'Class;
Name : in Value) return String is
begin
if Self.Impl = null then
raise NO_PROPERTY;
end if;
return To_String (Self.Get_Value (-Name));
end Get;
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String is
begin
if Exists (Self, Name) then
return Get (Self, Name);
else
return Default;
end if;
end Get;
procedure Check_And_Create_Impl (Self : in out Manager) is
begin
if Self.Impl = null then
-- Util.Properties.Factories.Initialize (Self);
Self.Impl := new Property_Map;
Util.Concurrent.Counters.Increment (Self.Impl.Count);
elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then
declare
Old : Interface_P.Manager_Access := Self.Impl;
Is_Zero : Boolean;
begin
Self.Impl := Create_Copy (Self.Impl.all);
Util.Concurrent.Counters.Increment (Self.Impl.Count);
Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero);
if Is_Zero then
Free (Old);
end if;
end;
end if;
end Check_And_Create_Impl;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Self.Set_Value (Name, To_Object (Item));
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value) is
begin
Self.Set_Value (Name, To_Object (Item));
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value) is
begin
Self.Set_Value (-Name, To_Object (Item));
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in String) is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property '" & Name & "'";
end if;
Check_And_Create_Impl (Self);
Remove (Self.Impl.all, +Name);
end Remove;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in Value) is
begin
Self.Remove (-Name);
end Remove;
-- ------------------------------
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
-- ------------------------------
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value)) is
begin
if Self.Impl /= null then
Self.Impl.Iterate (Process);
end if;
end Iterate;
-- ------------------------------
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
-- ------------------------------
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array is
begin
if Self.Impl = null then
declare
Empty : Name_Array (1 .. 0);
begin
return Empty;
end;
else
return Get_Names (Self.Impl.all, Prefix);
end if;
end Get_Names;
procedure Adjust (Object : in out Manager) is
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Increment (Object.Impl.Count);
end if;
end Adjust;
procedure Finalize (Object : in out Manager) is
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero);
if Is_Zero then
Free (Object.Impl);
end if;
end if;
end Finalize;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access) is
begin
if Self.Impl = null then
Self.Impl := Impl;
-- Self.Impl.Count := 1;
end if;
end Set_Property_Implementation;
procedure Load_Property (Name : out Unbounded_String;
Value : out Unbounded_String;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
pragma Unreferenced (Strip);
Line : Unbounded_String;
Pos : Natural;
Len : Natural;
begin
while not End_Of_File (File) loop
Line := Get_Line (File);
Len := Length (Line);
if Len /= 0 and then Element (Line, 1) /= '#' then
Pos := Index (Line, "=");
if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then
Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
elsif Pos > 0 and Prefix'Length = 0 then
Name := Head (Line, Pos - 1);
Value := Tail (Line, Len - Pos);
return;
end if;
end if;
end loop;
Name := Null_Unbounded_String;
Value := Null_Unbounded_String;
end Load_Property;
procedure Load_Properties (Self : in out Manager'Class;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
Name, Value : Unbounded_String;
begin
loop
Load_Property (Name, Value, File, Prefix, Strip);
exit when Name = Null_Unbounded_String;
Set (Self, Name, Value);
end loop;
exception
when End_Error =>
return;
end Load_Properties;
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False) is
F : File_Type;
begin
Open (F, In_File, Path);
Load_Properties (Self, F, Prefix, Strip);
Close (F);
end Load_Properties;
-- ------------------------------
-- Save the properties in the given file path.
-- ------------------------------
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "") is
procedure Save_Property (Name, Item : in Value);
Tmp : constant String := Path & ".tmp";
F : File_Type;
procedure Save_Property (Name, Item : in Value) is
begin
Put (F, Name);
Put (F, "=");
Put (F, Item);
New_Line (F);
end Save_Property;
-- Rename a file (the Ada.Directories.Rename does not allow to use the Unix atomic file rename!)
function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr;
Newpath : in Interfaces.C.Strings.chars_ptr) return Integer;
pragma Import (C, Sys_Rename, "rename");
Old_Path : Interfaces.C.Strings.chars_ptr;
New_Path : Interfaces.C.Strings.chars_ptr;
Result : Integer;
begin
Create (File => F, Name => Tmp);
Self.Iterate (Save_Property'Access);
Close (File => F);
-- Do a system atomic rename of old file in the new file.
-- Ada.Directories.Rename does not allow this.
Old_Path := Interfaces.C.Strings.New_String (Tmp);
New_Path := Interfaces.C.Strings.New_String (Path);
Result := Sys_Rename (Old_Path, New_Path);
Interfaces.C.Strings.Free (Old_Path);
Interfaces.C.Strings.Free (New_Path);
if Result /= 0 then
raise Ada.IO_Exceptions.Use_Error with "Cannot rename file";
end if;
end Save_Properties;
-- ------------------------------
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- ------------------------------
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False) is
Names : constant Name_Array := From.Get_Names;
begin
for I in Names'Range loop
declare
Name : Unbounded_String renames Names (I);
begin
if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then
if Strip and Prefix'Length > 0 then
declare
S : constant String := Slice (Name, Prefix'Length + 1, Length (Name));
begin
Self.Set (+(S), From.Get (Name));
end;
else
Self.Set (Name, From.Get (Name));
end if;
end if;
end;
end loop;
end Copy;
end Util.Properties;
|
Refactor the Properties implementation (step 1): - Declare the Property_Map type for the property representation - Implement the operations for the Property_Map - Update the Properties operation to use the new interface
|
Refactor the Properties implementation (step 1):
- Declare the Property_Map type for the property representation
- Implement the operations for the Property_Map
- Update the Properties operation to use the new interface
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1ddf832c8cc6f1ba6b4b78ff5d178399c81a260b
|
src/util-properties.ads
|
src/util-properties.ads
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
private with Util.Concurrent.Counters;
private with Util.Beans.Objects.Maps;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Ada.Strings.Unbounded.Unbounded_String;
function "+" (S : String) return Value renames To_Unbounded_String;
function "-" (S : Value) return String renames To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.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.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value));
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array;
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
end record;
type Manager_Access is access all Manager'Class;
type Manager_Factory is access function return Manager_Access;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value) is abstract;
-- 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 abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is abstract;
end Interface_P;
procedure Set_Property_Implementation (Self : in out Manager;
Impl : in Interface_P.Manager_Access);
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- properties -- Generic name/value property management
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
private with Util.Concurrent.Counters;
private with Util.Beans.Objects.Maps;
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Ada.Strings.Unbounded.Unbounded_String;
function "+" (S : String) return Value renames To_Unbounded_String;
function "-" (S : Value) return String renames To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.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.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Value) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return Value;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Value) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Value);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name, Item : Value));
type Name_Array is array (Natural range <>) of Value;
-- Return the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with
-- the prefix are returned.
function Get_Names (Self : in Manager;
Prefix : in String := "") return Name_Array;
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
end record;
type Manager_Access is access all Manager'Class;
type Manager_Factory is access function return Manager_Access;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value) is abstract;
-- 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 abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Refactor the Properties implementation (step 2): - Remove Set_Property_Implementation procedure
|
Refactor the Properties implementation (step 2):
- Remove Set_Property_Implementation procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b9e952ba60a764d8d3ef23a67e0ab0027a4eabf3
|
Ada/src/Problem_12.adb
|
Ada/src/Problem_12.adb
|
with Ada.Integer_Text_IO;
with Ada.Text_IO;
with PrimeInstances;
package body Problem_12 is
package IO renames Ada.Text_IO;
package I_IO renames Ada.Integer_Text_IO;
procedure Solve is
package Integer_Primes renames PrimeInstances.Integer_Primes;
sieve : constant Integer_Primes.Sieve := Integer_Primes.Generate_Sieve(15_000);
-- We actually have the count one higher than the actual count because
-- that's what we end up multiplying since '0' of the number is a choice.
type Factor_Array is Array (sieve'Range) of Positive;
function total_factors(factors: in Factor_Array) return Positive is
permutations : Positive := 1;
begin
for index in factors'Range loop
declare
count : constant Natural := factors(index);
begin
permutations := permutations * count;
end;
end loop;
return permutations;
end total_factors;
procedure generate_factors(num : in Positive; factors: out Factor_Array) is
quotient : Positive := num;
begin
for index in Factor_Array'Range loop
factors(index) := 1;
end loop;
for prime_index in sieve'Range loop
declare
prime : constant Positive := sieve(prime_index);
count : Natural := 1;
begin
while quotient mod prime = 0 loop
count := count + 1;
quotient := quotient / prime;
end loop;
if count > factors(prime_index) then
factors(prime_index) := count;
end if;
end;
end loop;
null;
end generate_factors;
factors : Factor_Array;
triangle : Positive := 1;
begin
for x in 2 .. sieve(sieve'Last) loop
triangle := triangle + x;
generate_factors(triangle, factors);
if total_factors(factors) > 500 then
I_IO.Put(triangle);
IO.New_Line;
exit;
end if;
end loop;
end Solve;
end Problem_12;
|
with Ada.Integer_Text_IO;
with Ada.Text_IO;
with PrimeInstances;
package body Problem_12 is
package IO renames Ada.Text_IO;
package I_IO renames Ada.Integer_Text_IO;
procedure Solve is
package Integer_Primes renames PrimeInstances.Integer_Primes;
sieve : constant Integer_Primes.Sieve := Integer_Primes.Generate_Sieve(15_000);
-- We actually have the count one higher than the actual count because
-- that's what we end up multiplying since '0' of the number is a choice.
type Factor_Array is Array (sieve'Range) of Positive;
function total_factors(max_prime_index : Positive; factors: in Factor_Array) return Positive is
permutations : Positive := 1;
begin
for index in factors'First .. max_prime_index loop
declare
count : constant Natural := factors(index);
begin
permutations := permutations * count;
end;
end loop;
return permutations;
end total_factors;
procedure generate_factors(num : in Positive; factors: in out Factor_Array; max_prime_index: out Positive) is
quotient : Positive := num;
begin
for prime_index in sieve'Range loop
declare
prime : constant Positive := sieve(prime_index);
count : Natural := 1;
begin
while quotient mod prime = 0 loop
max_prime_index := prime_index;
count := count + 1;
quotient := quotient / prime;
end loop;
if count > factors(prime_index) then
factors(prime_index) := count;
end if;
end;
end loop;
end generate_factors;
factors : Factor_Array;
triangle : Positive := 1;
max_prime_index : Positive;
begin
for index in Factor_Array'Range loop
factors(index) := 1;
end loop;
for x in 2 .. sieve(sieve'Last) loop
triangle := triangle + x;
generate_factors(triangle, factors, max_prime_index);
if total_factors(max_prime_index, factors) > 500 then
I_IO.Put(triangle);
IO.New_Line;
exit;
end if;
for index in factors'First .. max_prime_index loop
factors(index) := 1;
end loop;
end loop;
end Solve;
end Problem_12;
|
Make problem 12 twice as fast by limiting how far it proceeds through the permutations. I saw the problem on a random post about erlange so I decided to optimize mine until it could beat the haskell version someone posted. Still not there because this was a trivial change, but doubling speed is always good.
|
Make problem 12 twice as fast by limiting how far it proceeds through the permutations. I
saw the problem on a random post about erlange so I decided to optimize mine until it
could beat the haskell version someone posted. Still not there because this was a trivial
change, but doubling speed is always good.
|
Ada
|
unlicense
|
Tim-Tom/project-euler,Tim-Tom/project-euler,Tim-Tom/project-euler
|
cad3aca0a94a5cc7ce2aec1966ceb692b66d8215
|
awa/src/awa-applications.ads
|
awa/src/awa-applications.ads
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ADO.Sessions.Factory;
with AWA.Modules;
with AWA.Events;
with AWA.Events.Services;
package AWA.Applications is
-- Directories where the configuration files are searched.
package P_Module_Dir is
new ASF.Applications.Main.Configs.Parameter ("app.modules.dir",
"#{fn:composePath(app_search_dirs,'config')}");
-- A list of configuration files separated by ';'. These files are searched in
-- 'app.modules.dir' and loaded in the order specified.
package P_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml");
-- Module manager
--
-- The <b>Module_Manager</b> represents the root of the logic manager
type Application is new ASF.Applications.Main.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config);
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
overriding
procedure Initialize_Servlets (App : in out Application);
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
overriding
procedure Initialize_Filters (App : in out Application);
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
overriding
procedure Initialize_Components (App : in out Application);
-- Read the application configuration file <b>awa.xml</b>. This is called after the servlets
-- and filters have been registered in the application but before the module registration.
procedure Load_Configuration (App : in out Application);
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
procedure Initialize_Modules (App : in out Application);
-- Start the application. This is called by the server container when the server is started.
overriding
procedure Start (App : in out Application);
-- Register the module in the application
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "");
-- Get the database connection for reading
function Get_Session (App : Application)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session;
-- Register the module in the application
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "");
-- Find the module with the given name
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access;
-- Send the event in the application event queues.
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class);
-- Execute the <tt>Process</tt> procedure with the event manager used by the application.
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager));
-- Get the current application from the servlet context or service context.
function Current return Application_Access;
private
-- Initialize the parser represented by <b>Parser</b> to recognize the configuration
-- that are specific to the plugins that have been registered so far.
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class);
type Application is new ASF.Applications.Main.Application with record
DB_Factory : ADO.Sessions.Factory.Session_Factory;
Modules : aliased AWA.Modules.Module_Registry;
Events : aliased AWA.Events.Services.Event_Manager;
end record;
end AWA.Applications;
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 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 Util.Serialize.IO;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ADO.Sessions.Factory;
with AWA.Modules;
with AWA.Events;
with AWA.Events.Services;
package AWA.Applications is
-- Directories where the configuration files are searched.
package P_Module_Dir is
new ASF.Applications.Main.Configs.Parameter ("app.modules.dir",
"#{fn:composePath(app_search_dirs,'config')}");
-- A list of configuration files separated by ';'. These files are searched in
-- 'app.modules.dir' and loaded in the order specified before the application modules.
package P_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config", "awa.xml");
-- A list of configuration files separated by ';'. These files are searched in
-- 'app.modules.dir' and loaded in the order specified after all the application modules
-- are initialized.
package P_Plugin_Config_File is
new ASF.Applications.Main.Configs.Parameter ("app.config.plugins", "");
-- Module manager
--
-- The <b>Module_Manager</b> represents the root of the logic manager
type Application is new ASF.Applications.Main.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class);
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config);
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
overriding
procedure Initialize_Servlets (App : in out Application);
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
overriding
procedure Initialize_Filters (App : in out Application);
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
overriding
procedure Initialize_Components (App : in out Application);
-- Read the application configuration file <b>awa.xml</b>. This is called after the servlets
-- and filters have been registered in the application but before the module registration.
procedure Load_Configuration (App : in out Application;
Files : in String);
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
procedure Initialize_Modules (App : in out Application);
-- Start the application. This is called by the server container when the server is started.
overriding
procedure Start (App : in out Application);
-- Register the module in the application
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "");
-- Get the database connection for reading
function Get_Session (App : Application)
return ADO.Sessions.Session;
-- Get the database connection for writing
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session;
-- Register the module in the application
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "");
-- Find the module with the given name
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access;
-- Send the event in the application event queues.
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class);
-- Execute the <tt>Process</tt> procedure with the event manager used by the application.
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager));
-- Get the current application from the servlet context or service context.
function Current return Application_Access;
private
-- Initialize the parser represented by <b>Parser</b> to recognize the configuration
-- that are specific to the plugins that have been registered so far.
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class);
type Application is new ASF.Applications.Main.Application with record
DB_Factory : ADO.Sessions.Factory.Session_Factory;
Modules : aliased AWA.Modules.Module_Registry;
Events : aliased AWA.Events.Services.Event_Manager;
end record;
end AWA.Applications;
|
Change Load_Configuration to allow reading a custom configuration file New configuration property to define a configuration file for plugins
|
Change Load_Configuration to allow reading a custom configuration file
New configuration property to define a configuration file for plugins
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
59c65c579b5b4649b4bc651cec9da0d90bfb2b9a
|
src/security-auth-oauth.adb
|
src/security-auth-oauth.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
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.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Assoc_Handle := To_Unbounded_String ("nonce-generator");
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.OAuth.Clients;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
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.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
begin
Result.Assoc_Handle := To_Unbounded_String ("nonce-generator");
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
Initialize the issuer from the parameters
|
Initialize the issuer from the parameters
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
f2b06c10b0e0540fce692b2ca4c8e54790a94e6d
|
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,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,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 : u_sockaddr;
Peer_Len : socklen_t;
begin
loop
Accept_Connect(L,Peer,Peer_Len,S,Error);
exit when Error = 0;
pragma Assert(Error = EINTR);
end loop;
pragma Assert(S >= 0);
pragma Assert(Peer.addr_sock.sa_family = AF_INET);
-- Display local socket address
declare
Local_Addr : u_sockaddr;
Addr_Len : socklen_t;
Str_Addr : String(1..300);
Last : Natural := 0;
begin
Getsockname(S,Local_Addr,Addr_Len,Error);
pragma Assert(Error = 0);
pragma Assert(Local_Addr.addr_sock.sa_family = AF_INET);
Inet_Ntop(Local_Addr.addr_in.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
Put_Line("Local name is " & Str_Addr(1..Last) & ":" & ushort_t'Image(Ntohs(Local_Addr.addr_in.sin_port)));
end;
-- Display peer's address
declare
Str_Addr : String(1..300);
Last : Natural := 0;
Port : constant ushort_t := Ntohs(Peer.addr_in.sin_port);
begin
Inet_Ntop(Peer.addr_in.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
Put_Line("Received connect from " & Str_Addr(1..Last) & ":" & ushort_t'Image(Port));
-- Test Getpeername
declare
Peer_Name : u_sockaddr;
Name_Len : socklen_t;
Buf2 : String(1..300);
Last2 : Natural := 0;
begin
Getpeername(S,Peer_Name,Name_Len,Error);
pragma Assert(Error = 0);
pragma Assert(Peer_Name.addr_sock.sa_family = AF_INET);
Inet_Ntop(Peer_Name.addr_in.sin_addr,Buf2,Last2,Error);
pragma Assert(Error = 0);
pragma Assert(Buf2(1..Last2) = Str_Addr(1..Last));
Put_Line("Peer name is " & Str_Addr(1..Last) & ":" & ushort_t'Image(Ntohs(Peer_Name.addr_in.sin_port)));
end;
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;
declare
Linger : s_linger := ( l_onoff => 1, l_linger => 2 );
begin
Set_Sockopt(S,SOL_SOCKET,SO_LINGER,Linger,Error);
pragma Assert(Error = 0);
Linger.l_onoff := 0;
Linger.l_linger := 23;
Get_Sockopt(S,SOL_SOCKET,SO_LINGER,Linger,Error);
pragma Assert(Error = 0);
pragma Assert(Linger.l_onoff /= 0);
pragma Assert(Linger.l_linger = 2);
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;
with System;
use System;
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,Inet_C_Addr,Error);
pragma Assert(Error = 0);
-- Write something
declare
Msg : constant uchar_array := To_uchar_array("Hello!");
Count : Natural;
begin
Write(S,uchar_array(Msg),Count,Error);
pragma Assert(Error = 0);
pragma Assert(Count = Msg'Length);
end;
-- 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,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 : u_sockaddr;
Peer_Len : socklen_t;
begin
loop
Accept_Connect(L,Peer,Peer_Len,S,Error);
exit when Error = 0;
pragma Assert(Error = EINTR);
end loop;
pragma Assert(S >= 0);
pragma Assert(Peer.addr_sock.sa_family = AF_INET);
-- Display local socket address
declare
Local_Addr : u_sockaddr;
Addr_Len : socklen_t;
Str_Addr : String(1..300);
Last : Natural := 0;
begin
Getsockname(S,Local_Addr,Addr_Len,Error);
pragma Assert(Error = 0);
pragma Assert(Local_Addr.addr_sock.sa_family = AF_INET);
Inet_Ntop(Local_Addr.addr_in.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
Put_Line("Local name is " & Str_Addr(1..Last) & ":" & ushort_t'Image(Ntohs(Local_Addr.addr_in.sin_port)));
end;
-- Display peer's address
declare
Str_Addr : String(1..300);
Last : Natural := 0;
Port : constant ushort_t := Ntohs(Peer.addr_in.sin_port);
begin
Inet_Ntop(Peer.addr_in.sin_addr,Str_Addr,Last,Error);
pragma Assert(Error = 0);
Put_Line("Received connect from " & Str_Addr(1..Last) & ":" & ushort_t'Image(Port));
-- Test Getpeername
declare
Peer_Name : u_sockaddr;
Name_Len : socklen_t;
Buf2 : String(1..300);
Last2 : Natural := 0;
begin
Getpeername(S,Peer_Name,Name_Len,Error);
pragma Assert(Error = 0);
pragma Assert(Peer_Name.addr_sock.sa_family = AF_INET);
Inet_Ntop(Peer_Name.addr_in.sin_addr,Buf2,Last2,Error);
pragma Assert(Error = 0);
pragma Assert(Buf2(1..Last2) = Str_Addr(1..Last));
Put_Line("Peer name is " & Str_Addr(1..Last) & ":" & ushort_t'Image(Ntohs(Peer_Name.addr_in.sin_port)));
end;
end;
end;
#if POSIX_FAMILY = "FreeBSD" or POSIX_FAMILY = "Darwin"
-- Test KQueue
declare
Kq : fd_t;
Chgs : s_kevent_array(1..1);
Evts : s_kevent_array(1..1);
N_Evts : Natural := 0;
Timeout : constant s_timespec := ( tv_sec => 1, tv_nsec => 0 );
begin
KQueue(Kq,Error);
pragma Assert(Kq >= 0);
Chgs(1).ident := uint64_t(S);
Chgs(1).filter := EVFILT_READ;
Chgs(1).flags := EV_ADD;
Chgs(1).fflags := 0;
Chgs(1).udata := Null_Address;
loop
KEvent(Kq,Chgs,1,Timeout,Evts,N_Evts,Error);
pragma assert(Error = 0);
exit when N_Evts > 0;
end loop;
pragma Assert(N_Evts > 0);
pragma Assert(Evts(1).ident = uint64_t(S));
pragma Assert(Evts(1).filter = EVFILT_READ);
pragma Assert(Evts(1).data > 0);
pragma Assert(Evts(1).udata = Null_Address);
declare
Rx_Avail : constant Natural := Natural(Evts(1).data);
Rx_Buf : uchar_array(1..Rx_Avail);
Last : Natural;
begin
Read(S,Rx_Buf,Last,Error);
pragma Assert(Error = 0);
pragma Assert(Last = Rx_Avail);
Put("Got msg '");
Put(To_String(Rx_Buf(1..Last)));
Put_Line("'");
end;
Close(Kq,Error);
pragma Assert(Error = 0);
end;
#end if;
-- 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;
declare
Linger : s_linger := ( l_onoff => 1, l_linger => 2 );
begin
Set_Sockopt(S,SOL_SOCKET,SO_LINGER,Linger,Error);
pragma Assert(Error = 0);
Linger.l_onoff := 0;
Linger.l_linger := 23;
Get_Sockopt(S,SOL_SOCKET,SO_LINGER,Linger,Error);
pragma Assert(Error = 0);
pragma Assert(Linger.l_onoff /= 0);
pragma Assert(Linger.l_linger = 2);
end;
-- Close accepted socket
Close(S,Error);
pragma Assert(Error = 0);
end if;
end T0048;
|
Implement simple KQueue test
|
Implement simple KQueue test
|
Ada
|
lgpl-2.1
|
ve3wwg/adafpx,ve3wwg/adafpx
|
3e5bb0e4896069a093322090654b3407abe8921b
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
src/sqlite/ado-drivers-connections-sqlite.adb
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sqlite3_H;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.C;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
No_Callback : constant Sqlite3_H.sqlite3_callback := null;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
-- ------------------------------
-- Check for an error after executing a sqlite statement.
-- ------------------------------
procedure Check_Error (Connection : in Sqlite_Access;
Result : in int) is
begin
if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Error {0}: {1}", int'Image (Result), Msg);
end;
end if;
end Check_Error;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
-- Database.Execute ("begin transaction;");
null;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
-- Database.Execute ("commit transaction;");
null;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
-- Database.Execute ("rollback transaction;");
null;
end Rollback;
procedure Sqlite3_Free (Arg1 : Strings.chars_ptr);
pragma Import (C, sqlite3_free, "sqlite3_free");
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
use type Strings.chars_ptr;
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
Error_Msg : Strings.chars_ptr;
begin
Log.Debug ("Execute: {0}", SQL);
for Retry in 1 .. 100 loop
Result := Sqlite3_H.sqlite3_exec (Database.Server, ADO.C.To_C (SQL_Stat), No_Callback,
System.Null_Address, Error_Msg'Address);
exit when Result /= Sqlite3_H.SQLITE_BUSY;
delay 0.01 * Retry;
end loop;
Check_Error (Database.Server, Result);
if Error_Msg /= Strings.Null_Ptr then
Log.Error ("Error: {0}", Strings.Value (Error_Msg));
Sqlite3_Free (Error_Msg);
end if;
-- Free
-- Strings.Free (SQL_Stat);
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
pragma Unreferenced (Database);
Result : int;
begin
Log.Info ("Close connection");
-- if Database.Count = 1 then
-- Result := Sqlite3_H.sqlite3_close (Database.Server);
-- Database.Server := System.Null_Address;
-- end if;
pragma Unreferenced (Result);
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
Result : int;
begin
Log.Debug ("Release connection");
Result := Sqlite3_H.sqlite3_close (Database.Server);
Database.Server := System.Null_Address;
pragma Unreferenced (Result);
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
DB : Ref.Ref;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
pragma Unreferenced (D);
use Strings;
use type System.Address;
Name : constant String := To_String (Config.Database);
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased System.Address;
Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Log.Info ("Opening database {0}", Name);
if not DB.Is_Null then
Result := Ref.Create (DB.Value);
return;
end if;
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
raise DB_Error;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
Database.Execute (SQL);
end if;
end Configure;
begin
Database.Server := Handle;
Database.Name := Config.Database;
DB := Ref.Create (Database.all'Access);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Properties.Iterate (Process => Configure'Access);
Result := Ref.Create (Database.all'Access);
end;
end Create_Connection;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
end ADO.Drivers.Connections.Sqlite;
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sqlite3_H;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.C;
with ADO.Statements.Sqlite;
with ADO.Schemas.Sqlite;
package body ADO.Drivers.Connections.Sqlite is
use ADO.Statements.Sqlite;
use Interfaces.C;
pragma Linker_Options ("-lsqlite3");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite");
Driver_Name : aliased constant String := "sqlite";
Driver : aliased Sqlite_Driver;
No_Callback : constant Sqlite3_H.sqlite3_callback := null;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
-- ------------------------------
-- Check for an error after executing a sqlite statement.
-- ------------------------------
procedure Check_Error (Connection : in Sqlite_Access;
Result : in int) is
begin
if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then
declare
Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection);
Msg : constant String := Strings.Value (Error);
begin
Log.Error ("Error {0}: {1}", int'Image (Result), Msg);
end;
end if;
end Check_Error;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
-- Database.Execute ("begin transaction;");
null;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
begin
-- Database.Execute ("commit transaction;");
null;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
begin
-- Database.Execute ("rollback transaction;");
null;
end Rollback;
procedure Sqlite3_Free (Arg1 : Strings.chars_ptr);
pragma Import (C, sqlite3_free, "sqlite3_free");
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
use type Strings.chars_ptr;
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
Error_Msg : Strings.chars_ptr;
begin
Log.Debug ("Execute: {0}", SQL);
for Retry in 1 .. 100 loop
Result := Sqlite3_H.sqlite3_exec (Database.Server, ADO.C.To_C (SQL_Stat), No_Callback,
System.Null_Address, Error_Msg'Address);
exit when Result /= Sqlite3_H.SQLITE_BUSY;
delay 0.01 * Retry;
end loop;
Check_Error (Database.Server, Result);
if Error_Msg /= Strings.Null_Ptr then
Log.Error ("Error: {0}", Strings.Value (Error_Msg));
Sqlite3_Free (Error_Msg);
end if;
-- Free
-- Strings.Free (SQL_Stat);
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
pragma Unreferenced (Database);
Result : int;
begin
Log.Info ("Close connection");
-- if Database.Count = 1 then
-- Result := Sqlite3_H.sqlite3_close (Database.Server);
-- Database.Server := System.Null_Address;
-- end if;
pragma Unreferenced (Result);
end Close;
-- ------------------------------
-- Releases the sqlite connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
Result : int;
begin
Log.Debug ("Release connection");
Result := Sqlite3_H.sqlite3_close (Database.Server);
Database.Server := System.Null_Address;
pragma Unreferenced (Result);
end Finalize;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Sqlite.Load_Schema (Database, Schema);
end Load_Schema;
DB : Ref.Ref;
-- ------------------------------
-- Initialize the database connection manager.
-- ------------------------------
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
pragma Unreferenced (D);
use Strings;
Name : constant String := To_String (Config.Database);
Filename : Strings.chars_ptr;
Status : int;
Handle : aliased System.Address;
Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE;
begin
Log.Info ("Opening database {0}", Name);
if not DB.Is_Null then
Result := Ref.Create (DB.Value);
return;
end if;
Filename := Strings.New_String (Name);
Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access,
Flags,
Strings.Null_Ptr);
Strings.Free (Filename);
if Status /= Sqlite3_H.SQLITE_OK then
raise DB_Error;
end if;
declare
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name : in String;
Item : in Util.Properties.Value);
function Escape (Value : in Util.Properties.Value) return String;
function Escape (Value : in Util.Properties.Value) return String is
S : constant String := Util.Properties.To_String (Value);
begin
if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then
return S;
elsif S'Length > 0 and then S (S'First) = ''' then
return S;
else
return "'" & S & "'";
end if;
end Escape;
procedure Configure (Name : in String;
Item : in Util.Properties.Value) is
SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item);
begin
if Util.Strings.Index (Name, '.') = 0 then
Log.Info ("Configure database with {0}", SQL);
Database.Execute (SQL);
end if;
end Configure;
begin
Database.Server := Handle;
Database.Name := Config.Database;
DB := Ref.Create (Database.all'Access);
-- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands.
-- Typical configuration includes:
-- synchronous=OFF
-- temp_store=MEMORY
-- encoding='UTF-8'
Config.Properties.Iterate (Process => Configure'Access);
Result := Ref.Create (Database.all'Access);
end;
end Create_Connection;
-- ------------------------------
-- Initialize the SQLite driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing sqlite driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
end ADO.Drivers.Connections.Sqlite;
|
Remove unecessary use clause
|
Remove unecessary use clause
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
c80b3be4086e516b3d42dff82acc1f17b41c6e7f
|
awa/plugins/awa-settings/src/awa-settings-modules.ads
|
awa/plugins/awa-settings/src/awa-settings-modules.ads
|
-----------------------------------------------------------------------
-- awa-settings-modules -- Module awa-settings
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with Ada.Strings.Unbounded;
with AWA.Modules;
package AWA.Settings.Modules is
-- The name under which the module is registered.
NAME : constant String := "awa-settings";
type Setting_Manager is new AWA.Modules.Module_Manager with private;
type Setting_Manager_Access is access all Setting_Manager'Class;
-- Set the user setting with the given name in the setting manager cache
-- and in the database.
procedure Set (Manager : in out Setting_Manager;
Name : in String;
Value : in String);
-- Get the user setting with the given name from the setting manager cache.
-- Load the user setting from the database if necessary.
procedure Get (Manager : in out Setting_Manager;
Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String);
function Current return Setting_Manager_Access;
-- ------------------------------
-- Module awa-settings
-- ------------------------------
type Setting_Module is new AWA.Modules.Module with private;
type Setting_Module_Access is access all Setting_Module'Class;
-- Initialize the awa-settings module.
overriding
procedure Initialize (Plugin : in out Setting_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the awa-settings module.
function Get_Setting_Module return Setting_Module_Access;
private
type Setting_Module is new AWA.Modules.Module with null record;
type Setting_Data;
type Setting_Data_Access is access all Setting_Data;
type Setting_Data is limited record
Next_Setting : Setting_Data_Access;
Name : Ada.Strings.Unbounded.Unbounded_String;
Value : Ada.Strings.Unbounded.Unbounded_String;
end record;
protected type Settings is
procedure Get (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String);
procedure Set (Name : in String;
Value : in String);
procedure Clear;
private
First : Setting_Data_Access := null;
end Settings;
type Setting_Manager is new AWA.Modules.Module_Manager with record
Data : Settings;
end record;
end AWA.Settings.Modules;
|
-----------------------------------------------------------------------
-- awa-settings-modules -- Module awa-settings
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with Ada.Strings.Unbounded;
with AWA.Modules;
package AWA.Settings.Modules is
-- The name under which the module is registered.
NAME : constant String := "awa-settings";
-- The settings manager controls the creation and update of user settings.
-- It maintains a small LRU cache of user settings that have been loaded and
-- used by the application. The settings manager is intended to be stored as
-- an HTTP session attribute.
type Setting_Manager is new AWA.Modules.Module_Manager with private;
type Setting_Manager_Access is access all Setting_Manager'Class;
-- Set the user setting with the given name in the setting manager cache
-- and in the database.
procedure Set (Manager : in out Setting_Manager;
Name : in String;
Value : in String);
-- Get the user setting with the given name from the setting manager cache.
-- Load the user setting from the database if necessary.
procedure Get (Manager : in out Setting_Manager;
Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String);
function Current return Setting_Manager_Access;
-- ------------------------------
-- Module awa-settings
-- ------------------------------
type Setting_Module is new AWA.Modules.Module with private;
type Setting_Module_Access is access all Setting_Module'Class;
-- Initialize the awa-settings module.
overriding
procedure Initialize (Plugin : in out Setting_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the awa-settings module.
function Get_Setting_Module return Setting_Module_Access;
private
type Setting_Module is new AWA.Modules.Module with null record;
type Setting_Data;
type Setting_Data_Access is access all Setting_Data;
type Setting_Data is limited record
Next_Setting : Setting_Data_Access;
Name : Ada.Strings.Unbounded.Unbounded_String;
Value : Ada.Strings.Unbounded.Unbounded_String;
end record;
protected type Settings is
procedure Get (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String);
procedure Set (Name : in String;
Value : in String);
procedure Clear;
private
First : Setting_Data_Access := null;
end Settings;
type Setting_Manager is new AWA.Modules.Module_Manager with record
Data : Settings;
end record;
end AWA.Settings.Modules;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5421523d398295eacc4063c1d107a73b614da84e
|
src/ado-connections.ads
|
src/ado-connections.ads
|
-----------------------------------------------------------------------
-- ado-connections -- Database connections
-- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Statements;
with ADO.Schemas;
with ADO.Configs;
with Util.Strings;
with Util.Strings.Vectors;
with Util.Refs;
-- The `ADO.Connections` package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Connections is
use ADO.Statements;
-- Raised for all errors reported by the database.
Database_Error : exception;
type Driver is abstract tagged limited private;
type Driver_Access is access all Driver'Class;
subtype Driver_Index is ADO.Configs.Driver_Index range 1 .. ADO.Configs.Driver_Index'Last;
-- ------------------------------
-- Database connection implementation
-- ------------------------------
--
type Database_Connection is abstract new Util.Refs.Ref_Entity with record
Ident : String (1 .. 8) := (others => ' ');
end record;
type Database_Connection_Access is access all Database_Connection'Class;
-- Get the database driver index.
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index;
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is abstract;
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is abstract;
-- Create a delete statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is abstract;
-- Create an insert statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is abstract;
-- Create an update statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is abstract;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Database_Connection) is abstract;
-- Commit the current transaction.
procedure Commit (Database : in out Database_Connection) is abstract;
-- Rollback the current transaction.
procedure Rollback (Database : in out Database_Connection) is abstract;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is abstract;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Database_Connection)
return Driver_Access is abstract;
-- Closes the database connection
procedure Close (Database : in out Database_Connection) is abstract;
package Ref is
new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class,
Element_Access => Database_Connection_Access);
-- ------------------------------
-- The database configuration properties
-- ------------------------------
type Configuration is new ADO.Configs.Configuration with null record;
-- Get the driver index that corresponds to the driver for this database connection string.
function Get_Driver (Config : in Configuration) return Driver_Index;
-- Create a new connection using the configuration parameters.
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class)
with Post => not Result.Is_Null;
-- ------------------------------
-- Database Driver
-- ------------------------------
-- Create a new connection using the configuration parameters.
procedure Create_Connection (D : in out Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is abstract
with Post'Class => not Result.Is_Null;
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
procedure Create_Database (D : in out Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is abstract;
-- Get the driver unique index.
function Get_Driver_Index (D : in Driver) return Driver_Index;
-- Get the driver name.
function Get_Driver_Name (D : in Driver) return String;
-- Register a database driver.
procedure Register (Driver : in Driver_Access);
-- Get a database driver given its name.
function Get_Driver (Name : in String) return Driver_Access;
private
type Driver is abstract new Ada.Finalization.Limited_Controlled with record
Name : Util.Strings.Name_Access;
Index : Driver_Index;
end record;
end ADO.Connections;
|
-----------------------------------------------------------------------
-- ado-connections -- Database connections
-- Copyright (C) 2010, 2011, 2012, 2016, 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 Ada.Finalization;
with ADO.Statements;
with ADO.Schemas;
with ADO.Configs;
with Util.Strings;
with Util.Strings.Vectors;
with Util.Refs;
-- The `ADO.Connections` package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Connections is
use ADO.Statements;
-- Raised for all errors reported by the database.
Database_Error : exception;
type Driver is abstract tagged limited private;
type Driver_Access is access all Driver'Class;
subtype Driver_Index is ADO.Configs.Driver_Index range 1 .. ADO.Configs.Driver_Index'Last;
-- ------------------------------
-- Database connection implementation
-- ------------------------------
--
type Database_Connection is abstract new Util.Refs.Ref_Entity with record
Ident : String (1 .. 8) := (others => ' ');
end record;
type Database_Connection_Access is access all Database_Connection'Class;
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is abstract;
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is abstract;
-- Create a delete statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is abstract;
-- Create an insert statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is abstract;
-- Create an update statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is abstract;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Database_Connection) is abstract;
-- Commit the current transaction.
procedure Commit (Database : in out Database_Connection) is abstract;
-- Rollback the current transaction.
procedure Rollback (Database : in out Database_Connection) is abstract;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is abstract;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Database_Connection)
return Driver_Access is abstract;
-- Closes the database connection
procedure Close (Database : in out Database_Connection) is abstract;
package Ref is
new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class,
Element_Access => Database_Connection_Access);
-- ------------------------------
-- The database configuration properties
-- ------------------------------
type Configuration is new ADO.Configs.Configuration with null record;
-- Get the driver index that corresponds to the driver for this database connection string.
function Get_Driver (Config : in Configuration) return Driver_Index;
-- Create a new connection using the configuration parameters.
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class)
with Post => not Result.Is_Null;
-- ------------------------------
-- Database Driver
-- ------------------------------
-- Create a new connection using the configuration parameters.
procedure Create_Connection (D : in out Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is abstract
with Post'Class => not Result.Is_Null;
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
procedure Create_Database (D : in out Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is abstract;
-- Get the driver unique index.
function Get_Driver_Index (D : in Driver) return Driver_Index;
-- Get the driver name.
function Get_Driver_Name (D : in Driver) return String;
-- Register a database driver.
procedure Register (Driver : in Driver_Access);
-- Get a database driver given its name.
function Get_Driver (Name : in String) return Driver_Access;
private
type Driver is abstract new Ada.Finalization.Limited_Controlled with record
Name : Util.Strings.Name_Access;
Index : Driver_Index;
end record;
end ADO.Connections;
|
Remove unused Get_Driver_Index function
|
Remove unused Get_Driver_Index function
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
629b63b871b91ecc7e98c9e46d1c52ec7072b990
|
regtests/util-streams-buffered-lzma-tests.adb
|
regtests/util-streams-buffered-lzma-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams
-- 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.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Util.Files;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Lzma.Tests is
use Util.Tests;
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write",
Test_Compress_Stream'Access);
end Add_Tests;
procedure Test_Compress_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma");
begin
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
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 => "LZMA stream");
end Test_Compress_Stream;
end Util.Streams.Buffered.Lzma.Tests;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams
-- 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.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Lzma.Tests is
use Util.Tests;
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write",
Test_Compress_Stream'Access);
end Add_Tests;
procedure Test_Compress_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma");
begin
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
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 => "LZMA stream");
end Test_Compress_Stream;
end Util.Streams.Buffered.Lzma.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1b939f4f5f7a4ec9188454d053465abd16c18465
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Objects;
with ADO.Sessions;
with Security.Permissions;
with ASF.Applications;
with AWA.Modules;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Users.Services;
with AWA.Users.Models;
with AWA.Events;
private with Ada.Strings.Unbounded;
-- == Events ==
-- The *workspaces* module provides several events that are posted when some action are performed.
--
-- === invite-user ===
-- This event is posted when an invitation is created for a user. The event can be used to
-- send the associated invitation email to the invitee. The event contains the following
-- attributes:
--
-- key
-- email
-- name
-- message
-- inviter
--
-- === accept-invitation ===
-- This event is posted when an invitation is accepted by a user.
package AWA.Workspaces.Modules is
subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array;
Not_Found : exception;
-- The name under which the module is registered.
NAME : constant String := "workspaces";
-- The configuration parameter that defines the list of permissions to grant
-- to a user when his workspace is created.
PARAM_PERMISSIONS_LIST : constant String := "permissions_list";
package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user");
package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation");
-- ------------------------------
-- Module workspaces
-- ------------------------------
type Workspace_Module is new AWA.Modules.Module with private;
type Workspace_Module_Access is access all Workspace_Module'Class;
-- Initialize the workspaces module.
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Workspace_Module;
Props : in ASF.Applications.Config);
-- Get the list of permissions for the workspace owner.
function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array;
-- Get the workspace module.
function Get_Workspace_Module return Workspace_Module_Access;
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref);
-- Load the invitation from the access key and verify that the key is still valid.
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref);
-- Accept the invitation identified by the access key.
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String);
-- Send the invitation to the user.
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
-- Delete the member from the workspace. Remove the invitation if there is one.
procedure Delete_Member (Module : in Workspace_Module;
Member_Id : in ADO.Identifier);
-- Add a list of permissions for all the users of the workspace that have the appropriate
-- role. Workspace members will be able to access the given database entity for the
-- specified list of permissions.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Objects.Object_Ref'Class;
Workspace : in ADO.Identifier;
List : in Security.Permissions.Permission_Index_Array);
private
type Workspace_Module is new AWA.Modules.Module with record
User_Manager : AWA.Users.Services.User_Service_Access;
-- The list of permissions to grant to a user who creates the workspace.
Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String;
end record;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Objects;
with ADO.Sessions;
with Security.Permissions;
with ASF.Applications;
with AWA.Modules;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Users.Services;
with AWA.Users.Models;
with AWA.Events;
private with Ada.Strings.Unbounded;
-- == Events ==
-- The *workspaces* module provides several events that are posted when some action are performed.
--
-- === invite-user ===
-- This event is posted when an invitation is created for a user. The event can be used to
-- send the associated invitation email to the invitee. The event contains the following
-- attributes:
--
-- key
-- email
-- name
-- message
-- inviter
--
-- === accept-invitation ===
-- This event is posted when an invitation is accepted by a user.
package AWA.Workspaces.Modules is
subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array;
Not_Found : exception;
-- The name under which the module is registered.
NAME : constant String := "workspaces";
-- The configuration parameter that defines the list of permissions to grant
-- to a user when his workspace is created.
PARAM_PERMISSIONS_LIST : constant String := "permissions_list";
-- Permission to create a workspace.
package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create");
package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user");
package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation");
-- ------------------------------
-- Module workspaces
-- ------------------------------
type Workspace_Module is new AWA.Modules.Module with private;
type Workspace_Module_Access is access all Workspace_Module'Class;
-- Initialize the workspaces module.
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Workspace_Module;
Props : in ASF.Applications.Config);
-- Get the list of permissions for the workspace owner.
function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array;
-- Get the workspace module.
function Get_Workspace_Module return Workspace_Module_Access;
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref);
-- Load the invitation from the access key and verify that the key is still valid.
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref);
-- Accept the invitation identified by the access key.
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String);
-- Send the invitation to the user.
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class);
-- Delete the member from the workspace. Remove the invitation if there is one.
procedure Delete_Member (Module : in Workspace_Module;
Member_Id : in ADO.Identifier);
-- Add a list of permissions for all the users of the workspace that have the appropriate
-- role. Workspace members will be able to access the given database entity for the
-- specified list of permissions.
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Objects.Object_Ref'Class;
Workspace : in ADO.Identifier;
List : in Security.Permissions.Permission_Index_Array);
private
type Workspace_Module is new AWA.Modules.Module with record
User_Manager : AWA.Users.Services.User_Service_Access;
-- The list of permissions to grant to a user who creates the workspace.
Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String;
end record;
end AWA.Workspaces.Modules;
|
Declare the ACL_Create_Workspace permission
|
Declare the ACL_Create_Workspace permission
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d4c2193611f5f35c19f4b4ab0e7851a4a1dbec25
|
src/util-files.adb
|
src/util-files.adb
|
-----------------------------------------------------------------------
-- Util.Files -- Various File Utility Packages
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
use Ada.Directories;
use Ada.Strings;
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Natural;
Last : constant Natural := Path'Last;
begin
case Going is
when Forward =>
Pos := Path'First;
while Pos <= Last loop
Sep_Pos := Index (Path, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
Dir : constant String := Path (Pos .. Sep_Pos);
Done : Boolean;
begin
Process (Dir => Dir, Done => Done);
exit when Done;
end;
Pos := Sep_Pos + 2;
end loop;
when Backward =>
Pos := Path'Last;
while Pos >= Path'First loop
Sep_Pos := Index (Path, ";", Pos, Backward);
if Sep_Pos = 0 then
Sep_Pos := Path'First;
else
Sep_Pos := Sep_Pos + 1;
end if;
declare
Dir : constant String := Path (Sep_Pos .. Pos);
Done : Boolean;
begin
Process (Dir => Dir, Done => Done);
exit when Done or Sep_Pos = Path'First;
end;
Pos := Sep_Pos - 2;
end loop;
end case;
end Iterate_Path;
-- ------------------------------
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : String;
Paths : String) return String is
use Ada.Directories;
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Index (Paths, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String) return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Unbounded_String;
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
use Ada.Strings.Fixed;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Length (Result) > 0 then
Append (Result, ';');
end if;
Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return To_String (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 or Directory = "." or Directory = "./" then
return Name;
elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\')) then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
end Util.Files;
|
-----------------------------------------------------------------------
-- Util.Files -- Various File Utility Packages
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Fixed;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Util.Strings.Tokenizers;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => Path,
Pattern => ";",
Process => Process,
Going => Going);
end Iterate_Path;
-- ------------------------------
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : String;
Paths : String) return String is
use Ada.Directories;
use Ada.Strings.Fixed;
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Index (Paths, ";", Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String) return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Unbounded_String;
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
use Ada.Strings.Fixed;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Length (Result) > 0 then
Append (Result, ';');
end if;
Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return To_String (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 or Directory = "." or Directory = "./" then
return Name;
elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\')) then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
end Util.Files;
|
Use the string tokenizer to iterate over the search paths
|
Use the string tokenizer to iterate over the search paths
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
399473597573bad5a8c7259bd73c9750844de118
|
src/wiki-utils.adb
|
src/wiki-utils.adb
|
-----------------------------------------------------------------------
-- wiki-utils -- Wiki utility operations
-- 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.Parsers;
with Wiki.Render.Text;
with Wiki.Render.Html;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Streams.Builders;
with Wiki.Streams.Html.Builders;
with Wiki.Documents;
package body Wiki.Utils is
-- ------------------------------
-- Render the wiki text according to the wiki syntax in HTML into a string.
-- ------------------------------
function To_Html (Text : in Wiki.Strings.WString;
Syntax : in Wiki.Wiki_Syntax) return String is
Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Doc : Wiki.Documents.Document;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Engine : Wiki.Parsers.Parser;
begin
Renderer.Set_Output_Stream (Stream'Unchecked_Access);
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Syntax);
Engine.Parse (Text, Doc);
Renderer.Render (Doc);
return Stream.To_String;
end To_Html;
-- ------------------------------
-- Render the wiki text according to the wiki syntax in text into a string.
-- Wiki formatting and decoration are removed.
-- ------------------------------
function To_Text (Text : in Wiki.Strings.WString;
Syntax : in Wiki.Wiki_Syntax) return String is
Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream;
Doc : Wiki.Documents.Document;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
Engine : Wiki.Parsers.Parser;
begin
Renderer.Set_Output_Stream (Stream'Unchecked_Access);
Engine.Set_Syntax (Syntax);
Engine.Parse (Text, Doc);
Renderer.Render (Doc);
return Stream.To_String;
end To_Text;
end Wiki.Utils;
|
-----------------------------------------------------------------------
-- wiki-utils -- Wiki utility operations
-- 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.Parsers;
with Wiki.Render.Text;
with Wiki.Render.Html;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Streams.Builders;
with Wiki.Streams.Html.Builders;
with Wiki.Documents;
package body Wiki.Utils is
-- ------------------------------
-- Render the wiki text according to the wiki syntax in HTML into a string.
-- ------------------------------
function To_Html (Text : in Wiki.Strings.WString;
Syntax : in Wiki.Wiki_Syntax) return String is
Stream : aliased Wiki.Streams.Html.Builders.Html_Output_Builder_Stream;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Doc : Wiki.Documents.Document;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Engine : Wiki.Parsers.Parser;
begin
Renderer.Set_Output_Stream (Stream'Unchecked_Access);
Renderer.Set_Render_TOC (True);
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Syntax);
Engine.Parse (Text, Doc);
Renderer.Render (Doc);
return Stream.To_String;
end To_Html;
-- ------------------------------
-- Render the wiki text according to the wiki syntax in text into a string.
-- Wiki formatting and decoration are removed.
-- ------------------------------
function To_Text (Text : in Wiki.Strings.WString;
Syntax : in Wiki.Wiki_Syntax) return String is
Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream;
Doc : Wiki.Documents.Document;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
Engine : Wiki.Parsers.Parser;
begin
Renderer.Set_Output_Stream (Stream'Unchecked_Access);
Engine.Set_Syntax (Syntax);
Engine.Parse (Text, Doc);
Renderer.Render (Doc);
return Stream.To_String;
end To_Text;
end Wiki.Utils;
|
Set the TOC rendering
|
Set the TOC rendering
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
c114e285a3b212c243b2e9696f0b4cb13d714d37
|
tests/natools-s_expressions-file_rw_tests.adb
|
tests/natools-s_expressions-file_rw_tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Strings.Unbounded;
with Ada.Unchecked_Deallocation;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Atom_Refs;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.File_Writers;
with Natools.S_Expressions.Test_Tools;
with GNAT.Debug_Pools;
package body Natools.S_Expressions.File_RW_Tests is
package Stream_IO renames Ada.Streams.Stream_IO;
subtype String_Holder is Ada.Strings.Unbounded.Unbounded_String;
function Hold (S : String) return String_Holder
renames Ada.Strings.Unbounded.To_Unbounded_String;
function To_String (H : String_Holder) return String
renames Ada.Strings.Unbounded.To_String;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Atom_IO (Report);
S_Expression_IO (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Atom_IO (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Atom-based reading");
Payload : Atom (0 .. 255);
Temporary_File_Name : String_Holder;
begin
for I in Payload'Range loop
Payload (I) := Octet (I);
end loop;
Build_File :
declare
File : Stream_IO.File_Type;
begin
Stream_IO.Create (File, Stream_IO.Out_File, "");
Stream_IO.Write (File, Payload);
Temporary_File_Name := Hold (Stream_IO.Name (File));
Stream_IO.Close (File);
end Build_File;
Read_Test :
declare
Reader : File_Readers.Atom_Reader
:= File_Readers.Reader (To_String (Temporary_File_Name));
begin
Test_Tools.Test_Atom (Test, Payload, Reader.Read);
Small_Read :
declare
Buffer : Atom (1 .. 100) := (others => 0);
Length : Count;
begin
Reader.Read (Buffer, Length);
Test_Tools.Test_Atom
(Test, Payload (0 .. Buffer'Length - 1), Buffer);
if Length /= Payload'Length then
Test.Fail ("Expected total length"
& Count'Image (Payload'Length)
& " in small read, found"
& Count'Image (Length));
end if;
end Small_Read;
Large_Read :
declare
Buffer : Atom (1 .. 512) := (others => 0);
Length : Count;
begin
Reader.Read (Buffer, Length);
Test_Tools.Test_Atom
(Test, Payload, Buffer (Buffer'First .. Length));
Test_Tools.Test_Atom
(Test,
(1 .. Buffer'Length - Length => 0),
Buffer (Length + 1 .. Buffer'Last));
end Large_Read;
Reader.Set_Filename (To_String (Temporary_File_Name));
Buffer_Read :
declare
Buffer : Atom_Buffers.Atom_Buffer;
begin
Reader.Read (Buffer, 100);
Test_Tools.Test_Atom (Test, Payload, Buffer.Data);
end Buffer_Read;
Reference_Read :
declare
Buffer : Atom_Refs.Reference;
begin
Buffer := Reader.Read;
Test_Tools.Test_Atom (Test, Payload, Buffer.Query.Data.all);
end Reference_Read;
Block_Read :
declare
procedure Process (Block : in Atom);
Offset : Count := 0;
procedure Process (Block : in Atom) is
Next : constant Count := Offset + Block'Length;
begin
Test_Tools.Test_Atom
(Test, Payload (Offset .. Next - 1), Block);
Offset := Next;
end Process;
begin
Reader.Block_Query (100, Process'Access);
if Offset /= Payload'Last + 1 then
Test.Fail ("Expected final offset"
& Count'Image (Payload'Last + 1)
& ", found"
& Count'Image (Offset));
end if;
Offset := 0;
Reader.Block_Query (350, Process'Access);
if Offset /= Payload'Last + 1 then
Test.Fail ("Expected second final offset"
& Count'Image (Payload'Last + 1)
& ", found"
& Count'Image (Offset));
end if;
end Block_Read;
Heap_Read :
declare
procedure Tester (Data : in Atom);
procedure Raiser (Data : in Atom);
Local_Exception : exception;
procedure Tester (Data : in Atom) is
begin
Test_Tools.Test_Atom (Test, Payload, Data);
end Tester;
procedure Raiser (Data : in Atom) is
begin
raise Local_Exception;
end Raiser;
Pool : GNAT.Debug_Pools.Debug_Pool;
type Local_Atom_Access is access Atom;
for Local_Atom_Access'Storage_Pool use Pool;
procedure Unchecked_Deallocation is new Ada.Unchecked_Deallocation
(Atom, Local_Atom_Access);
procedure Query is new File_Readers.Query
(Local_Atom_Access, Unchecked_Deallocation);
begin
Query (Reader, Tester'Access);
begin
Query (Reader, Raiser'Access);
exception
when Local_Exception => null;
end;
end Heap_Read;
end Read_Test;
exception
when Error : others => Test.Report_Exception (Error);
end Atom_IO;
procedure S_Expression_IO (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("S-expression writing and re-reading");
Temporary_File_Name, Secondary_File_Name : String_Holder;
begin
First_Write :
declare
Writer : File_Writers.Writer := File_Writers.Create ("");
begin
Temporary_File_Name := Hold (Writer.Name);
Writer.Append_Atom (To_Atom ("begin"));
Writer.Open_List;
Writer.Open_List;
Writer.Close_List;
Writer.Open_List;
Writer.Append_Atom (To_Atom ("head"));
Writer.Append_Atom (To_Atom ("tail"));
Writer.Close_List;
Writer.Close_List;
Writer.Append_Atom (To_Atom ("end"));
Writer.Create ("");
Secondary_File_Name := Hold (Writer.Name);
Writer.Open_List;
Writer.Append_Atom (To_Atom ("first"));
Writer.Append_Atom (To_Atom ("last"));
Writer.Close_List;
end First_Write;
First_Read :
declare
Reader : File_Readers.S_Reader
:= File_Readers.Reader (To_String (Temporary_File_Name));
begin
Test_Tools.Test_Atom_Accessors (Test, Reader, To_Atom ("begin"), 0);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("head"), 2);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("tail"), 2);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("end"), 0);
Test_Tools.Next_And_Check (Test, Reader, Events.End_Of_Input, 0);
Reader.Rewind;
Test_Tools.Test_Atom_Accessors (Test, Reader, To_Atom ("begin"), 0);
Reader.Set_Filename (To_String (Secondary_File_Name));
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("first"), 1);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("last"), 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Reader, Events.End_Of_Input, 0);
end First_Read;
Second_Write :
declare
Writer : File_Writers.Writer
:= File_Writers.Open (To_String (Temporary_File_Name));
begin
Writer.Open_List;
Writer.Append_Atom (To_Atom ("foo"));
Writer.Append_Atom (To_Atom ("bar"));
Writer.Open_List;
Writer.Close_List;
Writer.Close_List;
Writer.Open (To_String (Secondary_File_Name));
Writer.Open_List;
Writer.Append_Atom (To_Atom ("unfinished"));
end Second_Write;
Raw_Read :
begin
Test_Tools.Test_Atom
(Test,
To_Atom ("5:begin(()(4:head4:tail))3:end(3:foo3:bar())"),
File_Readers.Reader (To_String (Temporary_File_Name)).Read);
Test_Tools.Test_Atom
(Test,
To_Atom ("(5:first4:last)(10:unfinished"),
File_Readers.Reader (To_String (Secondary_File_Name)).Read);
end Raw_Read;
exception
when Error : others => Test.Report_Exception (Error);
end S_Expression_IO;
end Natools.S_Expressions.File_RW_Tests;
|
------------------------------------------------------------------------------
-- 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. --
------------------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Strings.Unbounded;
with Ada.Unchecked_Deallocation;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Atom_Refs;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.File_Writers;
with Natools.S_Expressions.Test_Tools;
with GNAT.Debug_Pools;
package body Natools.S_Expressions.File_RW_Tests is
package Stream_IO renames Ada.Streams.Stream_IO;
subtype String_Holder is Ada.Strings.Unbounded.Unbounded_String;
function Hold (S : String) return String_Holder
renames Ada.Strings.Unbounded.To_Unbounded_String;
function To_String (H : String_Holder) return String
renames Ada.Strings.Unbounded.To_String;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Atom_IO (Report);
S_Expression_IO (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Atom_IO (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Atom-based reading");
Payload : Atom (0 .. 255);
Temporary_File_Name : String_Holder;
begin
for I in Payload'Range loop
Payload (I) := Octet (I);
end loop;
Build_File :
declare
File : Stream_IO.File_Type;
begin
Stream_IO.Create (File, Stream_IO.Out_File, "");
Stream_IO.Write (File, Payload);
Temporary_File_Name := Hold (Stream_IO.Name (File));
Stream_IO.Close (File);
end Build_File;
Read_Test :
declare
Reader : File_Readers.Atom_Reader
:= File_Readers.Reader (To_String (Temporary_File_Name));
begin
Test_Tools.Test_Atom (Test, Payload, Reader.Read);
Small_Read :
declare
Buffer : Atom (1 .. 100) := (others => 0);
Length : Count;
begin
Reader.Read (Buffer, Length);
Test_Tools.Test_Atom
(Test, Payload (0 .. Buffer'Length - 1), Buffer);
if Length /= Payload'Length then
Test.Fail ("Expected total length"
& Count'Image (Payload'Length)
& " in small read, found"
& Count'Image (Length));
end if;
end Small_Read;
Large_Read :
declare
Buffer : Atom (1 .. 512) := (others => 0);
Length : Count;
begin
Reader.Read (Buffer, Length);
Test_Tools.Test_Atom
(Test, Payload, Buffer (Buffer'First .. Length));
Test_Tools.Test_Atom
(Test,
(1 .. Buffer'Length - Length => 0),
Buffer (Length + 1 .. Buffer'Last));
end Large_Read;
Reader.Set_Filename (To_String (Temporary_File_Name));
Buffer_Read :
declare
Buffer : Atom_Buffers.Atom_Buffer;
begin
Reader.Read (Buffer, 100);
Test_Tools.Test_Atom (Test, Payload, Buffer.Data);
end Buffer_Read;
Reference_Read :
declare
Buffer : Atom_Refs.Reference;
begin
Buffer := Reader.Read;
Test_Tools.Test_Atom (Test, Payload, Buffer.Query.Data.all);
end Reference_Read;
Block_Read :
declare
procedure Process (Block : in Atom);
Offset : Count := 0;
procedure Process (Block : in Atom) is
Next : constant Count := Offset + Block'Length;
begin
Test_Tools.Test_Atom
(Test, Payload (Offset .. Next - 1), Block);
Offset := Next;
end Process;
begin
Reader.Block_Query (100, Process'Access);
if Offset /= Payload'Last + 1 then
Test.Fail ("Expected final offset"
& Count'Image (Payload'Last + 1)
& ", found"
& Count'Image (Offset));
end if;
Offset := 0;
Reader.Block_Query (350, Process'Access);
if Offset /= Payload'Last + 1 then
Test.Fail ("Expected second final offset"
& Count'Image (Payload'Last + 1)
& ", found"
& Count'Image (Offset));
end if;
end Block_Read;
Heap_Read :
declare
procedure Tester (Data : in Atom);
procedure Raiser (Data : in Atom);
Local_Exception : exception;
procedure Tester (Data : in Atom) is
begin
Test_Tools.Test_Atom (Test, Payload, Data);
end Tester;
procedure Raiser (Data : in Atom) is
begin
raise Local_Exception;
end Raiser;
Pool : GNAT.Debug_Pools.Debug_Pool;
type Local_Atom_Access is access Atom;
for Local_Atom_Access'Storage_Pool use Pool;
procedure Unchecked_Deallocation is new Ada.Unchecked_Deallocation
(Atom, Local_Atom_Access);
procedure Query is new File_Readers.Query
(Local_Atom_Access, Unchecked_Deallocation);
begin
Query (Reader, Tester'Access);
begin
Query (Reader, Raiser'Access);
exception
when Local_Exception => null;
end;
end Heap_Read;
end Read_Test;
exception
when Error : others => Test.Report_Exception (Error);
end Atom_IO;
procedure S_Expression_IO (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("S-expression writing and re-reading");
Temporary_File_Name, Secondary_File_Name : String_Holder;
begin
First_Write :
declare
Writer : File_Writers.Writer := File_Writers.Create ("");
begin
Temporary_File_Name := Hold (Writer.Name);
Writer.Append_Atom (To_Atom ("begin"));
Writer.Open_List;
Writer.Open_List;
Writer.Close_List;
Writer.Open_List;
Writer.Append_Atom (To_Atom ("head"));
Writer.Append_Atom (To_Atom ("tail"));
Writer.Close_List;
Writer.Close_List;
Writer.Append_Atom (To_Atom ("end"));
Writer.Create ("");
Secondary_File_Name := Hold (Writer.Name);
Writer.Open_List;
Writer.Append_Atom (To_Atom ("first"));
Writer.Append_Atom (To_Atom ("last"));
Writer.Close_List;
end First_Write;
First_Read :
declare
Reader : File_Readers.S_Reader
:= File_Readers.Reader (To_String (Temporary_File_Name));
begin
Test_Tools.Test_Atom_Accessors (Test, Reader, To_Atom ("begin"), 0);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("head"), 2);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("tail"), 2);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("end"), 0);
Test_Tools.Next_And_Check (Test, Reader, Events.End_Of_Input, 0);
Reader.Rewind;
Test_Tools.Test_Atom_Accessors (Test, Reader, To_Atom ("begin"), 0);
Reader.Set_Filename (To_String (Secondary_File_Name));
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("first"), 1);
Test_Tools.Next_And_Check (Test, Reader, To_Atom ("last"), 1);
Test_Tools.Next_And_Check (Test, Reader, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Reader, Events.End_Of_Input, 0);
end First_Read;
Second_Write :
declare
Writer : File_Writers.Writer
:= File_Writers.Open (To_String (Temporary_File_Name));
begin
Writer.Open_List;
Writer.Append_Atom (To_Atom ("foo"));
Writer.Append_Atom (To_Atom ("bar"));
Writer.Open_List;
Writer.Close_List;
Writer.Close_List;
Writer.Open (To_String (Secondary_File_Name));
Writer.Open_List;
Writer.Append_Atom (To_Atom ("unfinished"));
end Second_Write;
Raw_Read :
begin
Test_Tools.Test_Atom
(Test,
To_Atom ("5:begin(()(4:head4:tail))3:end(3:foo3:bar())"),
File_Readers.Reader (To_String (Temporary_File_Name)).Read);
Test_Tools.Test_Atom
(Test,
To_Atom ("(5:first4:last)(10:unfinished"),
File_Readers.Reader (To_String (Secondary_File_Name)).Read);
end Raw_Read;
Clear_Secondary :
declare
File : Stream_IO.File_Type;
begin
Stream_IO.Open
(File, Stream_IO.Out_File, To_String (Secondary_File_Name));
Stream_IO.Delete (File);
Check_Removal :
begin
Stream_IO.Open
(File, Stream_IO.Out_File, To_String (Secondary_File_Name));
Test.Error ("Expected exception wasn't triggered.");
return;
exception
when Stream_IO.Name_Error => null;
end Check_Removal;
end Clear_Secondary;
Run_Open_Or_Create :
declare
Writer : File_Writers.Writer
:= File_Writers.Open_Or_Create (To_String (Temporary_File_Name));
begin
Writer.Open_List;
Writer.Append_String ("");
Writer.Close_List;
Writer.Open_Or_Create (To_String (Secondary_File_Name));
Writer.Open_List;
Writer.Append_String ("solo");
Writer.Close_List;
end Run_Open_Or_Create;
Check_Open_Or_Create :
begin
Test_Tools.Test_Atom
(Test,
To_Atom ("5:begin(()(4:head4:tail))3:end(3:foo3:bar())(0:)"),
File_Readers.Reader (To_String (Temporary_File_Name)).Read);
Test_Tools.Test_Atom
(Test,
To_Atom ("(4:solo)"),
File_Readers.Reader (To_String (Secondary_File_Name)).Read);
end Check_Open_Or_Create;
exception
when Error : others => Test.Report_Exception (Error);
end S_Expression_IO;
end Natools.S_Expressions.File_RW_Tests;
|
update to test Open_Or_Create primitives
|
s_expressions-file_rw_tests: update to test Open_Or_Create primitives
|
Ada
|
isc
|
faelys/natools
|
dd87f7ab856f660181166ddb8f5f217850e2e0a0
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- 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 AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Wikis.Parsers.Tests;
with AWA.Wikis.Writers.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.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.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;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Wikis.Writers.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.Modules.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.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.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Wikis.Parsers.Tests;
with AWA.Wikis.Writers.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Wikis.Writers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.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.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Build the new unit tests
|
Build the new unit tests
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
10d12f5332db1dbf6dfc33684dbf43935cb56a7a
|
src/asm-intrinsic/util-concurrent-counters.adb
|
src/asm-intrinsic/util-concurrent-counters.adb
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Concurrent.Counters is
function Sync_Sub_And_Fetch (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Sub_And_Fetch,
External_Name => "__sync_sub_and_fetch_4");
function Sync_Fetch_And_Add (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Fetch_And_Add,
External_Name => "__sync_fetch_and_add_4");
procedure Sync_Add (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Add,
External_Name => "__sync_add_and_fetch_4");
procedure Sync_Sub (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Sub,
External_Name => "__sync_sub_and_fetch_4");
-- ------------------------------
-- Increment the counter atomically.
-- ------------------------------
procedure Increment (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, 1);
end Increment;
-- ------------------------------
-- Increment the counter atomically and return the value before increment.
-- ------------------------------
procedure Increment (C : in out Counter;
Value : out Integer) is
begin
Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1));
end Increment;
-- ------------------------------
-- Decrement the counter atomically.
-- ------------------------------
procedure Decrement (C : in out Counter) is
use type Interfaces.Unsigned_32;
begin
Sync_Sub (C.Value'Unrestricted_Access, 1);
end Decrement;
-- ------------------------------
-- Decrement the counter atomically and return a status.
-- ------------------------------
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean) is
use type Interfaces.Unsigned_32;
Value : Interfaces.Unsigned_32;
begin
Value := Sync_Sub_And_Fetch (C.Value'Unrestricted_Access, 1);
Is_Zero := Value = 0;
end Decrement;
-- ------------------------------
-- Get the counter value
-- ------------------------------
function Value (C : in Counter) return Integer is
begin
return Integer (C.Value);
end Value;
end Util.Concurrent.Counters;
|
-----------------------------------------------------------------------
-- util-concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010, 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.
-----------------------------------------------------------------------
package body Util.Concurrent.Counters is
function Sync_Sub_And_Fetch (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Sub_And_Fetch,
External_Name => "__sync_sub_and_fetch_4");
function Sync_Fetch_And_Add (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32) return Interfaces.Unsigned_32;
pragma Import (Intrinsic, Sync_Fetch_And_Add,
External_Name => "__sync_fetch_and_add_4");
procedure Sync_Add (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Add,
External_Name => "__sync_add_and_fetch_4");
procedure Sync_Sub (Ptr : access Interfaces.Unsigned_32;
Value : in Interfaces.Unsigned_32);
pragma Import (Intrinsic, Sync_Sub,
External_Name => "__sync_sub_and_fetch_4");
-- ------------------------------
-- Increment the counter atomically.
-- ------------------------------
procedure Increment (C : in out Counter) is
begin
Sync_Add (C.Value'Unrestricted_Access, 1);
end Increment;
-- ------------------------------
-- Increment the counter atomically and return the value before increment.
-- ------------------------------
procedure Increment (C : in out Counter;
Value : out Integer) is
begin
Value := Integer (Sync_Fetch_And_Add (C.Value'Unrestricted_Access, 1));
end Increment;
-- ------------------------------
-- Decrement the counter atomically.
-- ------------------------------
procedure Decrement (C : in out Counter) is
use type Interfaces.Unsigned_32;
begin
Sync_Sub (C.Value'Unrestricted_Access, 1);
end Decrement;
-- ------------------------------
-- Decrement the counter atomically and return a status.
-- ------------------------------
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean) is
use type Interfaces.Unsigned_32;
Value : Interfaces.Unsigned_32;
begin
Value := Sync_Sub_And_Fetch (C.Value'Unrestricted_Access, 1);
Is_Zero := Value = 0;
end Decrement;
-- ------------------------------
-- Get the counter value
-- ------------------------------
function Value (C : in Counter) return Integer is
begin
return Integer (C.Value);
end Value;
end Util.Concurrent.Counters;
|
Update the header
|
Update the header
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
54a7de52db4d3f42acfca4a52f0234c3f4e7d957
|
arch/RISC-V/SiFive/svd/FE310/fe310_svd-pwm.ads
|
arch/RISC-V/SiFive/svd/FE310/fe310_svd-pwm.ads
|
-- This spec has been automatically generated from FE310.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package FE310_SVD.PWM is
pragma Preelaborate;
---------------
-- Registers --
---------------
subtype CONFIG_SCALE_Field is HAL.UInt4;
-- PWM Configuration Register.
type CONFIG_Register is record
SCALE : CONFIG_SCALE_Field := 16#0#;
-- unspecified
Reserved_4_7 : HAL.UInt4 := 16#0#;
STICKY : Boolean := False;
ZEROCMP : Boolean := False;
DEGLITCH : Boolean := False;
-- unspecified
Reserved_11_11 : HAL.Bit := 16#0#;
ENALWAYS : Boolean := False;
ENONESHOT : Boolean := False;
-- unspecified
Reserved_14_15 : HAL.UInt2 := 16#0#;
CMP_CENTER_0 : Boolean := False;
CMP_CENTER_1 : Boolean := False;
CMP_CENTER_2 : Boolean := False;
CMP_CENTER_3 : Boolean := False;
-- unspecified
Reserved_20_23 : HAL.UInt4 := 16#0#;
CMP_GANG_0 : Boolean := False;
CMP_GANG_1 : Boolean := False;
CMP_GANG_2 : Boolean := False;
CMP_GANG_3 : Boolean := False;
CMP_IP_0 : Boolean := False;
CMP_IP_1 : Boolean := False;
CMP_IP_2 : Boolean := False;
CMP_IP_3 : Boolean := False;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CONFIG_Register use record
SCALE at 0 range 0 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
STICKY at 0 range 8 .. 8;
ZEROCMP at 0 range 9 .. 9;
DEGLITCH at 0 range 10 .. 10;
Reserved_11_11 at 0 range 11 .. 11;
ENALWAYS at 0 range 12 .. 12;
ENONESHOT at 0 range 13 .. 13;
Reserved_14_15 at 0 range 14 .. 15;
CMP_CENTER_0 at 0 range 16 .. 16;
CMP_CENTER_1 at 0 range 17 .. 17;
CMP_CENTER_2 at 0 range 18 .. 18;
CMP_CENTER_3 at 0 range 19 .. 19;
Reserved_20_23 at 0 range 20 .. 23;
CMP_GANG_0 at 0 range 24 .. 24;
CMP_GANG_1 at 0 range 25 .. 25;
CMP_GANG_2 at 0 range 26 .. 26;
CMP_GANG_3 at 0 range 27 .. 27;
CMP_IP_0 at 0 range 28 .. 28;
CMP_IP_1 at 0 range 29 .. 29;
CMP_IP_2 at 0 range 30 .. 30;
CMP_IP_3 at 0 range 31 .. 31;
end record;
subtype COUNT_16_CNT_Field is HAL.UInt31;
-- PWM Count Register.
type COUNT_16_Register is record
CNT : COUNT_16_CNT_Field := 16#0#;
-- unspecified
Reserved_31_31 : HAL.Bit := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COUNT_16_Register use record
CNT at 0 range 0 .. 30;
Reserved_31_31 at 0 range 31 .. 31;
end record;
subtype COUNT_8_CNT_Field is HAL.UInt23;
-- PWM Count Register.
type COUNT_8_Register is record
CNT : COUNT_8_CNT_Field := 16#0#;
-- unspecified
Reserved_23_31 : HAL.UInt9 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COUNT_8_Register use record
CNT at 0 range 0 .. 22;
Reserved_23_31 at 0 range 23 .. 31;
end record;
subtype SCALE_COUNT_16_CNT_Field is HAL.UInt16;
-- PWM Scaled Conunter Register.
type SCALE_COUNT_16_Register is record
CNT : SCALE_COUNT_16_CNT_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SCALE_COUNT_16_Register use record
CNT at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype SCALE_COUNT_8_CNT_Field is HAL.UInt9;
-- PWM Scaled Conunter Register.
type SCALE_COUNT_8_Register is record
CNT : SCALE_COUNT_8_CNT_Field := 16#0#;
-- unspecified
Reserved_9_31 : HAL.UInt23 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SCALE_COUNT_8_Register use record
CNT at 0 range 0 .. 8;
Reserved_9_31 at 0 range 9 .. 31;
end record;
subtype COMPARE_0_16_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_0_16_Register is record
COMPARE : COMPARE_0_16_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_0_16_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype COMPARE_0_8_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_0_8_Register is record
COMPARE : COMPARE_0_8_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_0_8_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype COMPARE_1_16_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_1_16_Register is record
COMPARE : COMPARE_1_16_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_1_16_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype COMPARE_1_8_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_1_8_Register is record
COMPARE : COMPARE_1_8_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_1_8_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype COMPARE_2_16_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_2_16_Register is record
COMPARE : COMPARE_2_16_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_2_16_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype COMPARE_2_8_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_2_8_Register is record
COMPARE : COMPARE_2_8_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_2_8_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype COMPARE_3_16_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_3_16_Register is record
COMPARE : COMPARE_3_16_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_3_16_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype COMPARE_3_8_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_3_8_Register is record
COMPARE : COMPARE_3_8_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_3_8_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
type PWM0_Disc is
(
PWM0_Disc_16,
PWM0_Disc_8);
-- Pulse-Width Modulation.
type PWM_Peripheral
(Discriminent : PWM0_Disc := PWM0_Disc_16)
is record
-- PWM Configuration Register.
CONFIG : aliased CONFIG_Register;
case Discriminent is
when PWM0_Disc_16 =>
-- PWM Count Register.
COUNT_16 : aliased COUNT_16_Register;
-- PWM Scaled Conunter Register.
SCALE_COUNT_16 : aliased SCALE_COUNT_16_Register;
-- PWM Compare Register.
COMPARE_0_16 : aliased COMPARE_0_16_Register;
-- PWM Compare Register.
COMPARE_1_16 : aliased COMPARE_1_16_Register;
-- PWM Compare Register.
COMPARE_2_16 : aliased COMPARE_2_16_Register;
-- PWM Compare Register.
COMPARE_3_16 : aliased COMPARE_3_16_Register;
when PWM0_Disc_8 =>
-- PWM Count Register.
COUNT_8 : aliased COUNT_8_Register;
-- PWM Scaled Conunter Register.
SCALE_COUNT_8 : aliased SCALE_COUNT_8_Register;
-- PWM Compare Register.
COMPARE_0_8 : aliased COMPARE_0_8_Register;
-- PWM Compare Register.
COMPARE_1_8 : aliased COMPARE_1_8_Register;
-- PWM Compare Register.
COMPARE_2_8 : aliased COMPARE_2_8_Register;
-- PWM Compare Register.
COMPARE_3_8 : aliased COMPARE_3_8_Register;
end case;
end record
with Unchecked_Union, Volatile;
for PWM_Peripheral use record
CONFIG at 16#0# range 0 .. 31;
COUNT_16 at 16#8# range 0 .. 31;
SCALE_COUNT_16 at 16#10# range 0 .. 31;
COMPARE_0_16 at 16#20# range 0 .. 31;
COMPARE_1_16 at 16#24# range 0 .. 31;
COMPARE_2_16 at 16#28# range 0 .. 31;
COMPARE_3_16 at 16#2C# range 0 .. 31;
COUNT_8 at 16#8# range 0 .. 31;
SCALE_COUNT_8 at 16#10# range 0 .. 31;
COMPARE_0_8 at 16#20# range 0 .. 31;
COMPARE_1_8 at 16#24# range 0 .. 31;
COMPARE_2_8 at 16#28# range 0 .. 31;
COMPARE_3_8 at 16#2C# range 0 .. 31;
end record;
-- Pulse-Width Modulation.
PWM0_Periph : aliased PWM_Peripheral
with Import, Address => System'To_Address (16#10015000#);
-- Pulse-Width Modulation.
PWM1_Periph : aliased PWM_Peripheral
with Import, Address => System'To_Address (16#10025000#);
-- Pulse-Width Modulation.
PWM2_Periph : aliased PWM_Peripheral
with Import, Address => System'To_Address (16#10035000#);
end FE310_SVD.PWM;
|
-- This spec has been automatically generated from FE310.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package FE310_SVD.PWM is
pragma Preelaborate;
---------------
-- Registers --
---------------
subtype CONFIG_SCALE_Field is HAL.UInt4;
-- CONFIG_CMP_CENTER array
type CONFIG_CMP_CENTER_Field_Array is array (0 .. 3) of Boolean
with Component_Size => 1, Size => 4;
-- Type definition for CONFIG_CMP_CENTER
type CONFIG_CMP_CENTER_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- CMP_CENTER as a value
Val : HAL.UInt4;
when True =>
-- CMP_CENTER as an array
Arr : CONFIG_CMP_CENTER_Field_Array;
end case;
end record
with Unchecked_Union, Size => 4;
for CONFIG_CMP_CENTER_Field use record
Val at 0 range 0 .. 3;
Arr at 0 range 0 .. 3;
end record;
-- CONFIG_CMP_GANG array
type CONFIG_CMP_GANG_Field_Array is array (0 .. 3) of Boolean
with Component_Size => 1, Size => 4;
-- Type definition for CONFIG_CMP_GANG
type CONFIG_CMP_GANG_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- CMP_GANG as a value
Val : HAL.UInt4;
when True =>
-- CMP_GANG as an array
Arr : CONFIG_CMP_GANG_Field_Array;
end case;
end record
with Unchecked_Union, Size => 4;
for CONFIG_CMP_GANG_Field use record
Val at 0 range 0 .. 3;
Arr at 0 range 0 .. 3;
end record;
-- CONFIG_CMP_IP array
type CONFIG_CMP_IP_Field_Array is array (0 .. 3) of Boolean
with Component_Size => 1, Size => 4;
-- Type definition for CONFIG_CMP_IP
type CONFIG_CMP_IP_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- CMP_IP as a value
Val : HAL.UInt4;
when True =>
-- CMP_IP as an array
Arr : CONFIG_CMP_IP_Field_Array;
end case;
end record
with Unchecked_Union, Size => 4;
for CONFIG_CMP_IP_Field use record
Val at 0 range 0 .. 3;
Arr at 0 range 0 .. 3;
end record;
-- PWM Configuration Register.
type CONFIG_Register is record
SCALE : CONFIG_SCALE_Field := 16#0#;
-- unspecified
Reserved_4_7 : HAL.UInt4 := 16#0#;
STICKY : Boolean := False;
ZEROCMP : Boolean := False;
DEGLITCH : Boolean := False;
-- unspecified
Reserved_11_11 : HAL.Bit := 16#0#;
ENALWAYS : Boolean := False;
ENONESHOT : Boolean := False;
-- unspecified
Reserved_14_15 : HAL.UInt2 := 16#0#;
CMP_CENTER : CONFIG_CMP_CENTER_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_20_23 : HAL.UInt4 := 16#0#;
CMP_GANG : CONFIG_CMP_GANG_Field :=
(As_Array => False, Val => 16#0#);
CMP_IP : CONFIG_CMP_IP_Field :=
(As_Array => False, Val => 16#0#);
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CONFIG_Register use record
SCALE at 0 range 0 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
STICKY at 0 range 8 .. 8;
ZEROCMP at 0 range 9 .. 9;
DEGLITCH at 0 range 10 .. 10;
Reserved_11_11 at 0 range 11 .. 11;
ENALWAYS at 0 range 12 .. 12;
ENONESHOT at 0 range 13 .. 13;
Reserved_14_15 at 0 range 14 .. 15;
CMP_CENTER at 0 range 16 .. 19;
Reserved_20_23 at 0 range 20 .. 23;
CMP_GANG at 0 range 24 .. 27;
CMP_IP at 0 range 28 .. 31;
end record;
subtype COUNT_CNT_Field is HAL.UInt31;
-- PWM Count Register.
type COUNT_Register is record
CNT : COUNT_CNT_Field := 16#0#;
-- unspecified
Reserved_31_31 : HAL.Bit := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COUNT_Register use record
CNT at 0 range 0 .. 30;
Reserved_31_31 at 0 range 31 .. 31;
end record;
subtype SCALE_COUNT_CNT_Field is HAL.UInt16;
-- PWM Scaled Conunter Register.
type SCALE_COUNT_Register is record
CNT : SCALE_COUNT_CNT_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SCALE_COUNT_Register use record
CNT at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype COMPARE_COMPARE_Field is HAL.UInt16;
-- PWM Compare Register.
type COMPARE_Register is record
COMPARE : COMPARE_COMPARE_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for COMPARE_Register use record
COMPARE at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Pulse-Width Modulation.
type PWM_Peripheral is record
-- PWM Configuration Register.
CONFIG : aliased CONFIG_Register;
-- PWM Count Register.
COUNT : aliased COUNT_Register;
-- PWM Scaled Conunter Register.
SCALE_COUNT : aliased SCALE_COUNT_Register;
-- PWM Compare Register.
COMPARE0 : aliased COMPARE_Register;
-- PWM Compare Register.
COMPARE1 : aliased COMPARE_Register;
-- PWM Compare Register.
COMPARE2 : aliased COMPARE_Register;
-- PWM Compare Register.
COMPARE3 : aliased COMPARE_Register;
end record
with Volatile;
for PWM_Peripheral use record
CONFIG at 16#0# range 0 .. 31;
COUNT at 16#8# range 0 .. 31;
SCALE_COUNT at 16#10# range 0 .. 31;
COMPARE0 at 16#20# range 0 .. 31;
COMPARE1 at 16#24# range 0 .. 31;
COMPARE2 at 16#28# range 0 .. 31;
COMPARE3 at 16#2C# range 0 .. 31;
end record;
-- Pulse-Width Modulation.
PWM0_Periph : aliased PWM_Peripheral
with Import, Address => System'To_Address (16#10015000#);
-- Pulse-Width Modulation.
PWM1_Periph : aliased PWM_Peripheral
with Import, Address => System'To_Address (16#10025000#);
-- Pulse-Width Modulation.
PWM2_Periph : aliased PWM_Peripheral
with Import, Address => System'To_Address (16#10035000#);
end FE310_SVD.PWM;
|
Update generated code with better description of PWM
|
FE310_SVD: Update generated code with better description of PWM
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
deb8951b59a0500065bf4a101a2920a267110dda
|
regtests/babel-base-users-tests.ads
|
regtests/babel-base-users-tests.ads
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Babel.Base.Users.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Find function resolving some existing user.
procedure Test_Find (T : in out Test);
-- Test the Get_Name operation.
procedure Test_Get_Name (T : in out Test);
end Babel.Base.Users.Tests;
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Babel.Base.Users.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Find function resolving some existing user.
procedure Test_Find (T : in out Test);
-- Test the Get_Name operation.
procedure Test_Get_Name (T : in out Test);
-- Test the Get_Uid operation.
procedure Test_Get_Uid (T : in out Test);
end Babel.Base.Users.Tests;
|
Declare the Test_Get_Uid procedure
|
Declare the Test_Get_Uid procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
892c70ebcbb6990bbda6d45826038de81743ea40
|
src/orka/implementation/orka-programs.adb
|
src/orka/implementation/orka-programs.adb
|
-- Copyright (c) 2015 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.Programs.Modules;
package body Orka.Programs is
function Create_Program (Modules : Programs.Modules.Module_Array;
Separable : Boolean := False) return Program is
begin
return Result : Program do
-- Attach all shaders to the program before linking
Programs.Modules.Attach_Shaders (Modules, Result);
Result.GL_Program.Link;
if not Result.GL_Program.Link_Status then
raise Program_Link_Error with Result.GL_Program.Info_Log;
end if;
end return;
end Create_Program;
function Create_Program (Module : Programs.Modules.Module;
Separable : Boolean := False) return Program is
begin
return Create_Program ((1 => Module));
end Create_Program;
function GL_Program (Object : Program) return GL.Objects.Programs.Program
is (Object.GL_Program);
procedure Use_Program (Object : Program) is
begin
Object.GL_Program.Use_Program;
-- TODO Only call if current program is a different object
end Use_Program;
function Attribute_Location (Object : Program; Name : String)
return GL.Attributes.Attribute is
begin
return Object.GL_Program.Attrib_Location (Name);
end Attribute_Location;
end Orka.Programs;
|
-- Copyright (c) 2015 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Orka.Programs.Modules;
package body Orka.Programs is
function Create_Program (Modules : Programs.Modules.Module_Array;
Separable : Boolean := False) return Program is
begin
return Result : Program do
-- Attach all shaders to the program before linking
Programs.Modules.Attach_Shaders (Modules, Result);
Result.GL_Program.Link;
if not Result.GL_Program.Link_Status then
raise Program_Link_Error with Result.GL_Program.Info_Log;
end if;
end return;
end Create_Program;
function Create_Program (Module : Programs.Modules.Module;
Separable : Boolean := False) return Program is
begin
return Create_Program (Modules.Module_Array'(1 => Module));
end Create_Program;
function GL_Program (Object : Program) return GL.Objects.Programs.Program
is (Object.GL_Program);
procedure Use_Program (Object : Program) is
begin
Object.GL_Program.Use_Program;
-- TODO Only call if current program is a different object
end Use_Program;
function Attribute_Location (Object : Program; Name : String)
return GL.Attributes.Attribute is
begin
return Object.GL_Program.Attrib_Location (Name);
end Attribute_Location;
end Orka.Programs;
|
Fix compilation with GNAT GPL 2016 (linking fails though)
|
orka: Fix compilation with GNAT GPL 2016 (linking fails though)
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
7abf1e30ab8c658b155afa5438a9336c1a8c6b25
|
src/wiki-parsers-html.adb
|
src/wiki-parsers-html.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Helpers;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String);
-- Parse a HTML/XML comment to strip it.
procedure Parse_Comment (P : in out Parser);
-- Parse a simple DOCTYPE declaration and ignore it.
procedure Parse_Doctype (P : in out Parser);
procedure Collect_Attributes (P : in out Parser);
function Is_Letter (C : in Wide_Wide_Character) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Letter (C : in Wide_Wide_Character) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wide_Wide_Character;
Token : Wide_Wide_Character;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Wiki.Helpers.Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wide_Wide_Character;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML/XML comment to strip it.
-- ------------------------------
procedure Parse_Comment (P : in out Parser) is
C : Wide_Wide_Character;
begin
Peek (P, C);
while not P.Is_Eof loop
Peek (P, C);
if C = '-' then
declare
Count : Natural := 1;
begin
Peek (P, C);
while not P.Is_Eof and C = '-' loop
Peek (P, C);
Count := Count + 1;
end loop;
exit when C = '>' and Count >= 2;
end;
end if;
end loop;
end Parse_Comment;
-- ------------------------------
-- Parse a simple DOCTYPE declaration and ignore it.
-- ------------------------------
procedure Parse_Doctype (P : in out Parser) is
C : Wide_Wide_Character;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = '>';
end loop;
end Parse_Doctype;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wide_Wide_Character;
Tag : Wiki.Html_Tag;
begin
Peek (P, C);
if C = '!' then
Peek (P, C);
if C = '-' then
Parse_Comment (P);
else
Parse_Doctype (P);
end if;
return;
end if;
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
Tag := Wiki.Find_Tag (To_Wide_Wide_String (Name));
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Tag);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Tag, P.Attributes);
End_Element (P, Tag);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Tag, P.Attributes);
end if;
end Parse_Element;
-- ------------------------------
-- Parse an HTML entity such as and replace it with the corresponding code.
-- ------------------------------
procedure Parse_Entity (P : in out Parser;
Token : in Wide_Wide_Character) is
pragma Unreferenced (Token);
Name : String (1 .. 10);
Len : Natural := 0;
High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last;
Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First;
Pos : Natural;
C : Wide_Wide_Character;
begin
while Len < Name'Last loop
Peek (P, C);
exit when C = ';' or else P.Is_Eof;
Len := Len + 1;
Name (Len) := Wiki.Strings.To_Char (C);
end loop;
while Low <= High loop
Pos := (Low + High) / 2;
if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then
Parse_Text (P, Entities.Mapping (Pos));
return;
elsif Entities.Keywords (Pos).all < Name (1 .. Len) then
Low := Pos + 1;
else
High := Pos - 1;
end if;
end loop;
-- The HTML entity is not recognized: we must treat it as plain wiki text.
Parse_Text (P, '&');
for I in 1 .. Len loop
Parse_Text (P, Wiki.Strings.To_WChar (Name (I)));
end loop;
end Parse_Entity;
end Wiki.Parsers.Html;
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Helpers;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String);
-- Parse a HTML/XML comment to strip it.
procedure Parse_Comment (P : in out Parser);
-- Parse a simple DOCTYPE declaration and ignore it.
procedure Parse_Doctype (P : in out Parser);
procedure Collect_Attributes (P : in out Parser);
function Is_Letter (C : in Wiki.Strings.WChar) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String);
function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String) is
C : Wiki.Strings.WChar;
begin
Name := To_Unbounded_Wide_Wide_String ("");
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wiki.Strings.WChar;
Token : Wiki.Strings.WChar;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Wiki.Helpers.Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
C : Wiki.Strings.WChar;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Attributes.Append (P.Attributes, Name, Value);
elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML/XML comment to strip it.
-- ------------------------------
procedure Parse_Comment (P : in out Parser) is
C : Wiki.Strings.WChar;
begin
Peek (P, C);
while not P.Is_Eof loop
Peek (P, C);
if C = '-' then
declare
Count : Natural := 1;
begin
Peek (P, C);
while not P.Is_Eof and C = '-' loop
Peek (P, C);
Count := Count + 1;
end loop;
exit when C = '>' and Count >= 2;
end;
end if;
end loop;
end Parse_Comment;
-- ------------------------------
-- Parse a simple DOCTYPE declaration and ignore it.
-- ------------------------------
procedure Parse_Doctype (P : in out Parser) is
C : Wiki.Strings.WChar;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = '>';
end loop;
end Parse_Doctype;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
Name : Unbounded_Wide_Wide_String;
C : Wiki.Strings.WChar;
Tag : Wiki.Html_Tag;
begin
Peek (P, C);
if C = '!' then
Peek (P, C);
if C = '-' then
Parse_Comment (P);
else
Parse_Doctype (P);
end if;
return;
end if;
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
Tag := Wiki.Find_Tag (To_Wide_Wide_String (Name));
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Tag);
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Tag, P.Attributes);
End_Element (P, Tag);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
Start_Element (P, Tag, P.Attributes);
end if;
end Parse_Element;
-- ------------------------------
-- Parse an HTML entity such as and replace it with the corresponding code.
-- ------------------------------
procedure Parse_Entity (P : in out Parser;
Token : in Wiki.Strings.WChar) is
pragma Unreferenced (Token);
Name : String (1 .. 10);
Len : Natural := 0;
High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last;
Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First;
Pos : Natural;
C : Wiki.Strings.WChar;
begin
while Len < Name'Last loop
Peek (P, C);
exit when C = ';' or else P.Is_Eof;
Len := Len + 1;
Name (Len) := Wiki.Strings.To_Char (C);
end loop;
while Low <= High loop
Pos := (Low + High) / 2;
if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then
Parse_Text (P, Entities.Mapping (Pos));
return;
elsif Entities.Keywords (Pos).all < Name (1 .. Len) then
Low := Pos + 1;
else
High := Pos - 1;
end if;
end loop;
-- The HTML entity is not recognized: we must treat it as plain wiki text.
Parse_Text (P, '&');
for I in 1 .. Len loop
Parse_Text (P, Wiki.Strings.To_WChar (Name (I)));
end loop;
end Parse_Entity;
end Wiki.Parsers.Html;
|
Use Wiki.Strings.WChar type
|
Use Wiki.Strings.WChar type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
3b72b46bdea6cbc5fb39a40062bce479c3ecc0ce
|
regtests/el-testsuite.adb
|
regtests/el-testsuite.adb
|
-----------------------------------------------------------------------
-- EL testsuite - EL Testsuite
-- 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 EL.Expressions;
with EL.Objects;
with EL.Contexts;
with EL.Contexts.Default;
with EL.Expressions.Tests;
with EL.Beans.Tests;
with EL.Contexts.Tests;
with EL.Utils.Tests;
package body EL.Testsuite is
use EL.Objects;
-- ------------------------------
-- Test object integer
-- ------------------------------
procedure Test_To_Object_Integer (T : in out Test) is
begin
declare
Value : constant EL.Objects.Object := To_Object (Integer (1));
begin
T.Assert (Condition => To_Integer (Value) = 1,
Message => "Object.To_Integer: invalid integer returned");
T.Assert (Condition => To_Long_Integer (Value) = 1,
Message => "Object.To_Long_Integer: invalid integer returned");
T.Assert (Condition => To_Boolean (Value),
Message => "Object.To_Boolean: invalid return");
declare
V2 : constant EL.Objects.Object := Value + To_Object (Long_Integer (100));
begin
T.Assert (Condition => To_Integer (V2) = 101,
Message => "To_Integer invalid after an add");
end;
end;
end Test_To_Object_Integer;
-- ------------------------------
-- Test object integer
-- ------------------------------
procedure Test_Expression (T : in out Test) is
E : EL.Expressions.Expression;
Value : Object;
Ctx : EL.Contexts.Default.Default_Context;
begin
-- Positive number
E := EL.Expressions.Create_Expression ("12345678901", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Long_Long_Integer (Value) = Long_Long_Integer (12345678901),
Message => "[1] Expression result invalid: " & To_String (Value));
-- Negative number
E := EL.Expressions.Create_Expression ("-10", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = -10,
Message => "[2] Expression result invalid: " & To_String (Value));
-- Simple add
E := EL.Expressions.Create_Expression ("#{1+1}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = 2,
Message => "[2.1] Expression result invalid: " & To_String (Value));
-- Constant expressions
E := EL.Expressions.Create_Expression ("#{12 + (123 - 3) * 4}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = 492,
Message => "[3] Expression result invalid: " & To_String (Value));
-- Constant expressions
E := EL.Expressions.Create_Expression ("#{12 + (123 - 3) * 4 + (23? 10 : 0)}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = 502,
Message => "[4] Expression result invalid: " & To_String (Value));
-- Choice expressions
E := EL.Expressions.Create_Expression ("#{1 > 2 ? 12 + 2 : 3 * 3}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = 9,
Message => "[5] Expression result invalid: " & To_String (Value));
-- Choice expressions using strings
E := EL.Expressions.Create_Expression ("#{1 > 2 ? 12 + 2 : 'A string'}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_String (Value) = "A string",
Message => "[6] Expression result invalid: " & To_String (Value));
end Test_Expression;
package Caller is new Util.Test_Caller (Test);
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
Caller.Add_Test (Ret, "Test To_Object (Integer)",
Test_To_Object_Integer'Access);
Caller.Add_Test (Ret, "Test Expressions", Test_Expression'Access);
EL.Expressions.Tests.Add_Tests (Ret);
EL.Contexts.Tests.Add_Tests (Ret);
EL.Beans.Tests.Add_Tests (Ret);
EL.Utils.Tests.Add_Tests (Ret);
return Ret;
end Suite;
end EL.Testsuite;
|
-----------------------------------------------------------------------
-- EL testsuite - EL Testsuite
-- 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 EL.Expressions;
with EL.Objects;
with EL.Contexts;
with EL.Contexts.Default;
with EL.Expressions.Tests;
with EL.Beans.Tests;
with EL.Contexts.Tests;
with EL.Utils.Tests;
package body EL.Testsuite is
use EL.Objects;
-- ------------------------------
-- Test object integer
-- ------------------------------
procedure Test_To_Object_Integer (T : in out Test) is
begin
declare
Value : constant EL.Objects.Object := To_Object (Integer (1));
begin
T.Assert (Condition => To_Integer (Value) = 1,
Message => "Object.To_Integer: invalid integer returned");
T.Assert (Condition => To_Long_Integer (Value) = 1,
Message => "Object.To_Long_Integer: invalid integer returned");
T.Assert (Condition => To_Boolean (Value),
Message => "Object.To_Boolean: invalid return");
declare
V2 : constant EL.Objects.Object := Value + To_Object (Long_Integer (100));
begin
T.Assert (Condition => To_Integer (V2) = 101,
Message => "To_Integer invalid after an add");
end;
end;
end Test_To_Object_Integer;
-- ------------------------------
-- Test object integer
-- ------------------------------
procedure Test_Expression (T : in out Test) is
E : EL.Expressions.Expression;
Value : Object;
Ctx : EL.Contexts.Default.Default_Context;
begin
-- Positive number
E := EL.Expressions.Create_Expression ("12345678901", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Long_Long_Integer (Value) = Long_Long_Integer (12345678901),
Message => "[1] Expression result invalid: " & To_String (Value));
-- Negative number
E := EL.Expressions.Create_Expression ("-10", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = -10,
Message => "[2] Expression result invalid: " & To_String (Value));
-- Simple add
E := EL.Expressions.Create_Expression ("#{1+1}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = 2,
Message => "[2.1] Expression result invalid: " & To_String (Value));
-- Constant expressions
E := EL.Expressions.Create_Expression ("#{12 + (123 - 3) * 4}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = 492,
Message => "[3] Expression result invalid: " & To_String (Value));
-- Constant expressions
E := EL.Expressions.Create_Expression ("#{12 + (123 - 3) * 4 + (23? 10 : 0)}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = 502,
Message => "[4] Expression result invalid: " & To_String (Value));
-- Choice expressions
E := EL.Expressions.Create_Expression ("#{1 > 2 ? 12 + 2 : 3 * 3}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_Integer (Value) = 9,
Message => "[5] Expression result invalid: " & To_String (Value));
-- Choice expressions using strings
E := EL.Expressions.Create_Expression ("#{1 > 2 ? 12 + 2 : 'A string'}", Ctx);
Value := E.Get_Value (Ctx);
T.Assert (Condition => To_String (Value) = "A string",
Message => "[6] Expression result invalid: " & To_String (Value));
end Test_Expression;
package Caller is new Util.Test_Caller (Test, "EL");
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
Caller.Add_Test (Ret, "Test To_Object (Integer)",
Test_To_Object_Integer'Access);
Caller.Add_Test (Ret, "Test Expressions", Test_Expression'Access);
EL.Expressions.Tests.Add_Tests (Ret);
EL.Contexts.Tests.Add_Tests (Ret);
EL.Beans.Tests.Add_Tests (Ret);
EL.Utils.Tests.Add_Tests (Ret);
return Ret;
end Suite;
end EL.Testsuite;
|
Use the test name EL
|
Use the test name EL
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
bd580b6362f56e3c38b4c966bb5123c729ec5b47
|
src/gen-artifacts-docs-markdown.adb
|
src/gen-artifacts-docs-markdown.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Markdown is
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".md";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
begin
Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
if Line.Kind = L_LIST then
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_LIST_ITEM then
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_START_CODE or Line.Kind = L_END_CODE then
if Formatter.Need_NewLine then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, "```");
else
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, Line.Content);
end if;
end Write_Line;
-- ------------------------------
-- Finish the document.
-- ------------------------------
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is
begin
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[Generated by Dynamo](https://github.com/stcarrez/dynamo) from _"
& Source & "_");
end Finish_Document;
end Gen.Artifacts.Docs.Markdown;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Artifacts.Docs.Markdown is
-- ------------------------------
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
-- ------------------------------
overriding
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is
begin
return Ada.Strings.Unbounded.To_String (Document.Name) & ".md";
end Get_Document_Name;
-- ------------------------------
-- Start a new document.
-- ------------------------------
overriding
procedure Start_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type) is
begin
Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title));
Ada.Text_IO.New_Line (File);
end Start_Document;
-- ------------------------------
-- Write a line in the target document formatting the line if necessary.
-- ------------------------------
overriding
procedure Write_Line (Formatter : in out Document_Formatter;
File : in Ada.Text_IO.File_Type;
Line : in Line_Type) is
begin
if Line.Kind = L_LIST then
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_LIST_ITEM then
Ada.Text_IO.Put (File, Line.Content);
Formatter.Need_Newline := True;
elsif Line.Kind = L_START_CODE or Line.Kind = L_END_CODE then
if Formatter.Need_NewLine then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, "```");
else
if Formatter.Need_Newline then
Ada.Text_IO.New_Line (File);
Formatter.Need_Newline := False;
end if;
Ada.Text_IO.Put_Line (File, Line.Content);
end if;
end Write_Line;
-- ------------------------------
-- Finish the document.
-- ------------------------------
overriding
procedure Finish_Document (Formatter : in out Document_Formatter;
Document : in File_Document;
File : in Ada.Text_IO.File_Type;
Source : in String) is
begin
Ada.Text_IO.New_Line (File);
Ada.Text_IO.Put_Line (File, "----");
Ada.Text_IO.Put_Line (File,
"[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *"
& Source & "*");
end Finish_Document;
end Gen.Artifacts.Docs.Markdown;
|
Fix formatting for GitHub markdown
|
Fix formatting for GitHub markdown
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
6e2a90f2223e8ec2046d5deb18c926cd8b429851
|
samples/multipro_refs.adb
|
samples/multipro_refs.adb
|
-----------------------------------------------------------------------
-- multipro_refs -- Points out multiprocessor issues with reference counters
-- Copyright (C) 2011, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with Util.Concurrent.Counters;
with Util.Measures;
with Ada.Text_IO;
with Util.Refs;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
procedure Multipro_Refs is
use Util.Log;
use Util.Concurrent.Counters;
Log : constant Loggers.Logger := Loggers.Create ("multipro");
type Data is new Util.Refs.Ref_Entity with record
Value : Natural;
Rand : Natural;
Result : Long_Long_Integer;
end record;
type Data_Access is access all Data;
package Data_Ref is new Util.Refs.References (Data, Data_Access);
package Atomic_Data_Ref is new Data_Ref.IR.Atomic;
package Hash_Map is new Ada.Containers.Indefinite_Hashed_Maps (String, String,
Ada.Strings.Hash,
"=");
type Cache is new Util.Refs.Ref_Entity with record
Map : Hash_Map.Map;
end record;
type Cache_Access is access all Cache;
package Hash_Ref is new Util.Refs.References (Cache, Cache_Access);
package Atomic_Hash_Ref is new Hash_Ref.IR.Atomic;
procedure Set_Reference (O : in Data_Ref.Ref);
function Exists (Key : in String) return Boolean;
function Find (Key : in String) return String;
procedure Add (Key : in String; Value : in String);
function Get_Reference return Data_Ref.Ref;
R : Atomic_Hash_Ref.Atomic_Ref;
function Exists (Key : in String) return Boolean is
C : constant Hash_Ref.Ref := R.Get;
begin
return C.Value.Map.Contains (Key);
end Exists;
function Find (Key : in String) return String is
C : constant Hash_Ref.Ref := R.Get;
begin
if C.Value.Map.Contains (Key) then
return C.Value.Map.Element (Key);
else
return "";
end if;
end Find;
procedure Add (Key : in String; Value : in String) is
C : constant Hash_Ref.Ref := R.Get;
N : constant Hash_Ref.Ref := Hash_Ref.Create;
begin
N.Value.Map := C.Value.Map;
N.Value.Map.Include (Key, Value);
R.Set (N);
end Add;
-- Target counter value we would like.
Max_Counter : constant Integer := 1_00_000;
-- Max number of tasks for executing the concurrent increment.
Max_Tasks : constant Integer := 16;
Unsafe_Ref : Data_Ref.Ref := Data_Ref.Create;
Safe_Ref : Atomic_Data_Ref.Atomic_Ref;
-- When <b>Run_Safe</b> is false, we use the Ada assignment to update a reference.
-- The program will crash at a random time due to corruption or multiple free.
--
-- When <b>Run_Safe</b> is true, we use the protected type Atomic_Ref to change
-- the shared reference. It will not crash.
Run_Safe : constant Boolean := True;
function Get_Reference return Data_Ref.Ref is
begin
if Run_Safe then
return Safe_Ref.Get;
else
return Unsafe_Ref;
end if;
end Get_Reference;
procedure Set_Reference (O : in Data_Ref.Ref) is
begin
if Run_Safe then
Safe_Ref.Set (O);
else
Unsafe_Ref := O;
end if;
end Set_Reference;
-- Performance measurement.
Perf : Util.Measures.Measure_Set;
T : Util.Measures.Stamp;
begin
Safe_Ref.Set (Data_Ref.Create);
Get_Reference.Value.Value := 0;
for Task_Count in 1 .. Max_Tasks loop
R.Set (Hash_Ref.Create);
declare
-- Each task will increment the counter by the following amount.
Increment_By_Task : constant Integer := Max_Counter / Task_Count;
-- Counter protected by concurrent accesses.
Counter : Util.Concurrent.Counters.Counter;
begin
declare
-- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by
-- the specified amount.
task type Worker is
entry Start (Count : in Natural;
Ident : in Integer);
end Worker;
task body Worker is
Cnt : Natural;
Id : Integer;
begin
accept Start (Count : in Natural;
Ident : in Integer) do
Cnt := Count;
Id := Ident;
end Start;
-- Get the data, compute something and change the reference.
for I in 1 .. Cnt loop
declare
Ref : constant Data_Ref.Ref := Get_Reference;
Ref2 : constant Data_Ref.Ref := Data_Ref.Create;
Key : constant String := "K" & Natural'Image (I / 10);
begin
Ref2.Value.Value := Ref.Value.Value + 1;
Ref2.Value.Rand := Cnt;
Ref2.Value.Result := Long_Long_Integer (Ref2.Value.Rand * Cnt)
* Long_Long_Integer (Ref2.Value.Value);
Set_Reference (Ref2);
Util.Concurrent.Counters.Increment (Counter);
if not Exists (Key) then
Add (Key, Natural'Image (I));
end if;
declare
S : constant String := Find (Key);
pragma Unreferenced (S);
begin
null;
exception
when others =>
Log.Info ("{0}: Find did not found the key: {1}",
Integer'Image (Id), Key);
end;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised: ", E, True);
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
Log.Info ("Starting " & Integer'Image (Task_Count) & " tasks");
for I in Tasks'Range loop
Tasks (I).Start (Increment_By_Task, I);
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
Util.Measures.Report (Measures => Perf,
S => T,
Title => "Increment counter with "
& Integer'Image (Task_Count) & " tasks");
Log.Info ("Data.Value := " & Natural'Image (Get_Reference.Value.Value));
Log.Info ("Data.Rand := " & Natural'Image (Get_Reference.Value.Rand));
Log.Info ("Data.Result := " & Long_Long_Integer'Image (Get_Reference.Value.Result));
end;
end loop;
-- Dump the result
Util.Measures.Write (Perf, "Multipro", Ada.Text_IO.Standard_Output);
end Multipro_Refs;
|
-----------------------------------------------------------------------
-- multipro_refs -- Points out multiprocessor issues with reference counters
-- Copyright (C) 2011, 2019, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with Util.Concurrent.Counters;
with Util.Measures;
with Ada.Text_IO;
with Util.Refs;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
procedure Multipro_Refs is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("multipro");
type Data is new Util.Refs.Ref_Entity with record
Value : Natural;
Rand : Natural;
Result : Long_Long_Integer;
end record;
type Data_Access is access all Data;
package Data_Ref is new Util.Refs.References (Data, Data_Access);
package Atomic_Data_Ref is new Data_Ref.IR.Atomic;
package Hash_Map is new Ada.Containers.Indefinite_Hashed_Maps (String, String,
Ada.Strings.Hash,
"=");
type Cache is new Util.Refs.Ref_Entity with record
Map : Hash_Map.Map;
end record;
type Cache_Access is access all Cache;
package Hash_Ref is new Util.Refs.References (Cache, Cache_Access);
package Atomic_Hash_Ref is new Hash_Ref.IR.Atomic;
procedure Set_Reference (O : in Data_Ref.Ref);
function Exists (Key : in String) return Boolean;
function Find (Key : in String) return String;
procedure Add (Key : in String; Value : in String);
function Get_Reference return Data_Ref.Ref;
R : Atomic_Hash_Ref.Atomic_Ref;
function Exists (Key : in String) return Boolean is
C : constant Hash_Ref.Ref := R.Get;
begin
return C.Value.Map.Contains (Key);
end Exists;
function Find (Key : in String) return String is
C : constant Hash_Ref.Ref := R.Get;
begin
if C.Value.Map.Contains (Key) then
return C.Value.Map.Element (Key);
else
return "";
end if;
end Find;
procedure Add (Key : in String; Value : in String) is
C : constant Hash_Ref.Ref := R.Get;
N : constant Hash_Ref.Ref := Hash_Ref.Create;
begin
N.Value.Map := C.Value.Map;
N.Value.Map.Include (Key, Value);
R.Set (N);
end Add;
-- Target counter value we would like.
Max_Counter : constant Integer := 1_00_000;
-- Max number of tasks for executing the concurrent increment.
Max_Tasks : constant Integer := 16;
Unsafe_Ref : Data_Ref.Ref := Data_Ref.Create;
Safe_Ref : Atomic_Data_Ref.Atomic_Ref;
-- When <b>Run_Safe</b> is false, we use the Ada assignment to update a reference.
-- The program will crash at a random time due to corruption or multiple free.
--
-- When <b>Run_Safe</b> is true, we use the protected type Atomic_Ref to change
-- the shared reference. It will not crash.
Run_Safe : constant Boolean := True;
function Get_Reference return Data_Ref.Ref is
begin
if Run_Safe then
return Safe_Ref.Get;
else
return Unsafe_Ref;
end if;
end Get_Reference;
procedure Set_Reference (O : in Data_Ref.Ref) is
begin
if Run_Safe then
Safe_Ref.Set (O);
else
Unsafe_Ref := O;
end if;
end Set_Reference;
-- Performance measurement.
Perf : Util.Measures.Measure_Set;
T : Util.Measures.Stamp;
begin
Safe_Ref.Set (Data_Ref.Create);
Get_Reference.Value.Value := 0;
for Task_Count in 1 .. Max_Tasks loop
R.Set (Hash_Ref.Create);
declare
-- Each task will increment the counter by the following amount.
Increment_By_Task : constant Integer := Max_Counter / Task_Count;
-- Counter protected by concurrent accesses.
Counter : Util.Concurrent.Counters.Counter;
begin
declare
-- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by
-- the specified amount.
task type Worker is
entry Start (Count : in Natural;
Ident : in Integer);
end Worker;
task body Worker is
Cnt : Natural;
Id : Integer;
begin
accept Start (Count : in Natural;
Ident : in Integer) do
Cnt := Count;
Id := Ident;
end Start;
-- Get the data, compute something and change the reference.
for I in 1 .. Cnt loop
declare
Ref : constant Data_Ref.Ref := Get_Reference;
Ref2 : constant Data_Ref.Ref := Data_Ref.Create;
Key : constant String := "K" & Natural'Image (I / 10);
begin
Ref2.Value.Value := Ref.Value.Value + 1;
Ref2.Value.Rand := Cnt;
Ref2.Value.Result := Long_Long_Integer (Ref2.Value.Rand * Cnt)
* Long_Long_Integer (Ref2.Value.Value);
Set_Reference (Ref2);
Util.Concurrent.Counters.Increment (Counter);
if not Exists (Key) then
Add (Key, Natural'Image (I));
end if;
declare
S : constant String := Find (Key);
pragma Unreferenced (S);
begin
null;
exception
when others =>
Log.Info ("{0}: Find did not found the key: {1}",
Integer'Image (Id), Key);
end;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised: ", E, True);
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
Log.Info ("Starting " & Integer'Image (Task_Count) & " tasks");
for I in Tasks'Range loop
Tasks (I).Start (Increment_By_Task, I);
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
Util.Measures.Report (Measures => Perf,
S => T,
Title => "Increment counter with "
& Integer'Image (Task_Count) & " tasks");
Log.Info ("Data.Value := " & Natural'Image (Get_Reference.Value.Value));
Log.Info ("Data.Rand := " & Natural'Image (Get_Reference.Value.Rand));
Log.Info ("Data.Result := " & Long_Long_Integer'Image (Get_Reference.Value.Result));
end;
end loop;
-- Dump the result
Util.Measures.Write (Perf, "Multipro", Ada.Text_IO.Standard_Output);
end Multipro_Refs;
|
Remove unused use type clause
|
Remove unused use type clause
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5ccc331467f449c8b169e49370c439b0fb9cfc89
|
src/asf-sessions-factory.adb
|
src/asf-sessions-factory.adb
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Sessions.Generate_Id (Rand);
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access
:= new Session_Record '(Ada.Finalization.Limited_Controlled with
Ref_Counter => Util.Concurrent.Counters.ONE,
Create_Time => Ada.Calendar.Clock,
Max_Inactive => Factory.Max_Inactive,
others => <>);
begin
Impl.Access_Time := Impl.Create_Time;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Sessions.Insert (Sess);
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Factory.Sessions.Find (Id);
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Factory.Sessions.Initialize;
end Initialize;
protected body Session_Cache is
-- ------------------------------
-- Find the session in the session cache.
-- ------------------------------
function Find (Id : in String) return Session is
Pos : constant Session_Maps.Cursor := Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
return Session_Maps.Element (Pos);
else
return Null_Session;
end if;
end Find;
-- ------------------------------
-- Insert the session in the session cache.
-- ------------------------------
procedure Insert (Sess : in Session) is
begin
Sessions.Insert (Sess.Impl.Id.all'Access, Sess);
end Insert;
-- ------------------------------
-- Generate a random bitstream.
-- ------------------------------
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : Stream_Element_Offset := Rand'Length / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate_Id;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
procedure Initialize is
begin
Id_Random.Reset (Random);
end Initialize;
end Session_Cache;
end ASF.Sessions.Factory;
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Sessions.Generate_Id (Rand);
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access
:= new Session_Record '(Ada.Finalization.Limited_Controlled with
Ref_Counter => Util.Concurrent.Counters.ONE,
Create_Time => Ada.Calendar.Clock,
Max_Inactive => Factory.Max_Inactive,
others => <>);
begin
Impl.Access_Time := Impl.Create_Time;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Sessions.Insert (Sess);
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Factory.Sessions.Find (Id);
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Factory.Sessions.Initialize;
end Initialize;
protected body Session_Cache is
-- ------------------------------
-- Find the session in the session cache.
-- ------------------------------
function Find (Id : in String) return Session is
Pos : constant Session_Maps.Cursor := Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
return Session_Maps.Element (Pos);
else
return Null_Session;
end if;
end Find;
-- ------------------------------
-- Insert the session in the session cache.
-- ------------------------------
procedure Insert (Sess : in Session) is
begin
Sessions.Insert (Sess.Impl.Id.all'Access, Sess);
end Insert;
-- ------------------------------
-- Generate a random bitstream.
-- ------------------------------
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : constant Stream_Element_Offset := Rand'Length / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate_Id;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
procedure Initialize is
begin
Id_Random.Reset (Random);
end Initialize;
end Session_Cache;
end ASF.Sessions.Factory;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
faeb1813aac4ab298a7305b93066f2efb825159d
|
src/gen-commands-database.adb
|
src/gen-commands-database.adb
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Exceptions;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Util.Processes;
with Util.Streams.Texts;
with Util.Streams.Pipes;
with ADO.Drivers.Connections;
with ADO.Sessions.Factory;
with ADO.Statements;
with ADO.Queries;
with ADO.Parameters;
with Gen.Database.Model;
package body Gen.Commands.Database is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database");
-- Check if the database with the given name exists.
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Check if the database with the given name has some tables.
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
procedure Execute_Command (Command : in String;
Input : in String);
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Generator : in out Gen.Generator.Handler);
-- Create the database identified by the given name.
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String);
-- Create the user and grant him access to the database.
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String);
-- ------------------------------
-- Check if the database with the given name exists.
-- ------------------------------
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Database_List);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
D : constant String := Stmt.Get_String (0);
begin
if Name = D then
return True;
end if;
end;
Stmt.Next;
end loop;
return False;
end Has_Database;
-- ------------------------------
-- Check if the database with the given name has some tables.
-- ------------------------------
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Table_List);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
return Stmt.Has_Elements;
end Has_Tables;
-- ------------------------------
-- Create the database identified by the given name.
-- ------------------------------
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String) is
use Ada.Strings.Unbounded;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Creating database '{0}'", Name);
Query.Set_Query (Gen.Database.Model.Query_Create_Database);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
end Create_Database;
-- ------------------------------
-- Create the user and grant him access to the database.
-- ------------------------------
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String) is
use Ada.Strings.Unbounded;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name);
if Password'Length > 0 then
Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password);
else
Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password);
end if;
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Bind_Param ("user", ADO.Parameters.Token (User));
if Password'Length > 0 then
Stmt.Bind_Param ("password", Password);
end if;
Stmt.Execute;
Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
end Create_User_Grant;
-- ------------------------------
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
-- ------------------------------
procedure Execute_Command (Command : in String;
Input : in String) is
Proc : aliased Util.Streams.Pipes.Pipe_Stream;
Text : Util.Streams.Texts.Reader_Stream;
begin
if Input /= "" then
Proc.Set_Input_Stream (Input);
end if;
Text.Initialize (Proc'Unchecked_Access);
Proc.Open (Command, Util.Processes.READ);
while not Text.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Text.Read_Line (Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Error ("{0}", Ada.Strings.Unbounded.To_String (Line));
end;
end loop;
Proc.Close;
if Proc.Get_Exit_Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Proc.Get_Exit_Status = 255 then
Log.Error ("Command not found: {0}", Command);
else
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Proc.Get_Exit_Status));
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read {0}", Input);
end Execute_Command;
-- ------------------------------
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
-- ------------------------------
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Generator : in out Gen.Generator.Handler) is
Database : constant String := Config.Get_Database;
Username : constant String := Config.Get_Property ("user");
Password : constant String := Config.Get_Property ("password");
Dir : constant String := Util.Files.Compose (Model, "mysql");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql");
begin
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
if Password'Length > 0 then
Execute_Command ("mysql --user=" & Username & " --password=" & Password & " "
& Database, File);
else
Execute_Command ("mysql --user=" & Username & " "
& Database, File);
end if;
end Create_Mysql_Tables;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name);
use Ada.Strings.Unbounded;
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String);
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String;
Username : in String;
Password : in String);
procedure Create_SQLite_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String);
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String;
Username : in String;
Password : in String) is
Factory : ADO.Sessions.Factory.Session_Factory;
Root_Connection : Unbounded_String;
Root_Hidden : Unbounded_String;
Pos : Natural;
begin
-- Build a connection string to create the database.
Pos := Util.Strings.Index (Database, ':');
Append (Root_Connection, Database (Database'First .. Pos));
Append (Root_Connection, "//");
Append (Root_Connection, Config.Get_Server);
if Config.Get_Port > 0 then
Append (Root_Connection, ':');
Append (Root_Connection, Util.Strings.Image (Config.Get_Port));
end if;
Append (Root_Connection, "/?user=");
Append (Root_Connection, Username);
Root_Connection := Root_Hidden;
if Password'Length > 0 then
Append (Root_Connection, "&password=");
Append (Root_Connection, Password);
Append (Root_Hidden, "&password=XXXXXXXX");
end if;
Log.Info ("Connecting to {0} for database setup", Root_Hidden);
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Factory.Create (To_String (Root_Connection));
declare
Name : constant String := Generator.Get_Project_Name;
DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session;
begin
-- Create the database only if it does not already exists.
if not Has_Database (DB, Config.Get_Database) then
Create_Database (DB, Config.Get_Database);
end if;
-- If some tables exist, don't try to create tables again.
-- We could improve by reading the current database schema, comparing with our
-- schema and create what is missing (new tables, new columns).
if Has_Tables (DB, Config.Get_Database) then
Generator.Error ("The database {0} exists", Config.Get_Database);
else
-- Create the user grant. On MySQL, it is safe to do this several times.
Create_User_Grant (DB, Config.Get_Database,
Config.Get_Property ("user"),
Config.Get_Property ("password"));
-- And now create the tables by using the SQL script generated by Dyanmo.
Create_Mysql_Tables (Name, Model, Config, Generator);
end if;
end;
end Create_MySQL_Database;
-- ------------------------------
-- Create the SQLite database.
-- ------------------------------
procedure Create_SQLite_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String) is
Name : constant String := Generator.Get_Project_Name;
Path : constant String := Config.Get_Database;
Dir : constant String := Util.Files.Compose (Model, "sqlite");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-sqlite.sql");
begin
if Ada.Directories.Exists (Path) then
Log.Info ("Connecting to {0} for database setup", Database);
end if;
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
Execute_Command ("sqlite3 --init " & File & " " & Path, "");
end Create_SQLite_Database;
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String) is
Config : ADO.Drivers.Connections.Configuration;
begin
Config.Set_Connection (Database);
if Config.Get_Database = "" then
Generator.Error ("Invalid database connection: no database name specified");
return;
end if;
if Config.Get_Driver = "mysql" then
if Config.Get_Property ("user") = "" then
Generator.Error ("Invalid database connection: missing user property");
return;
end if;
Create_MySQL_Database (Model, Config, Database, Username, Password);
elsif Config.Get_Driver = "sqlite" then
Create_SQLite_Database (Model, Config, Database);
else
Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver);
end if;
-- Remember the database connection string.
Generator.Set_Project_Property ("database", Database);
Generator.Save_Project;
exception
when E : others =>
Generator.Error (Ada.Exceptions.Exception_Message (E));
end Create_Database;
Model : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Arg1 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else "");
Arg2 : constant String := (if Args.Get_Count > 2 then Args.Get_Argument (3) else "");
Arg3 : constant String := (if Args.Get_Count > 3 then Args.Get_Argument (4) else "");
begin
Generator.Read_Project ("dynamo.xml");
-- Initialize the database drivers.
ADO.Drivers.Initialize (Generator.Get_Properties);
-- Check if a database is specified in the command line and use it.
if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then
Create_Database (Model, Arg1, Arg2, Arg3);
else
declare
Database : constant String := Generator.Get_Project_Property ("database");
begin
-- Otherwise, get the database identification from dynamo.xml configuration.
if Ada.Strings.Fixed.Index (Database, "://") = 0 then
Generator.Error ("No database specified.");
return;
end if;
Create_Database (Model, Database, Arg1, Arg2);
end;
end if;
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-database: Creates the database");
Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]");
New_Line;
Put_Line (" Create the database specified by the connection string.");
Put_Line (" The connection string has the form:");
Put_Line (" driver://host[:port]/database");
New_Line;
Put_Line (" The database must not exist. The user specified in the connection string");
Put_Line (" is granted the access to the new database.");
end Help;
end Gen.Commands.Database;
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Exceptions;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Util.Processes;
with Util.Streams.Texts;
with Util.Streams.Pipes;
with ADO.Drivers.Connections;
with ADO.Sessions.Factory;
with ADO.Statements;
with ADO.Queries;
with ADO.Parameters;
with Gen.Database.Model;
package body Gen.Commands.Database is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Database");
-- Check if the database with the given name exists.
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Check if the database with the given name has some tables.
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean;
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
procedure Execute_Command (Command : in String;
Input : in String);
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Generator : in out Gen.Generator.Handler);
-- Create the database identified by the given name.
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String);
-- Create the user and grant him access to the database.
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String);
-- ------------------------------
-- Check if the database with the given name exists.
-- ------------------------------
function Has_Database (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Database_List);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
D : constant String := Stmt.Get_String (0);
begin
if Name = D then
return True;
end if;
end;
Stmt.Next;
end loop;
return False;
end Has_Database;
-- ------------------------------
-- Check if the database with the given name has some tables.
-- ------------------------------
function Has_Tables (DB : in ADO.Sessions.Session'Class;
Name : in String) return Boolean is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Query.Set_Query (Gen.Database.Model.Query_Table_List);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
return Stmt.Has_Elements;
end Has_Tables;
-- ------------------------------
-- Create the database identified by the given name.
-- ------------------------------
procedure Create_Database (DB : in ADO.Sessions.Master_Session;
Name : in String) is
use Ada.Strings.Unbounded;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Creating database '{0}'", Name);
Query.Set_Query (Gen.Database.Model.Query_Create_Database);
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Execute;
end Create_Database;
-- ------------------------------
-- Create the user and grant him access to the database.
-- ------------------------------
procedure Create_User_Grant (DB : in ADO.Sessions.Master_Session;
Name : in String;
User : in String;
Password : in String) is
use Ada.Strings.Unbounded;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("Granting access for user '{0}' to database '{1}'", User, Name);
if Password'Length > 0 then
Query.Set_Query (Gen.Database.Model.Query_Create_User_With_Password);
else
Query.Set_Query (Gen.Database.Model.Query_Create_User_No_Password);
end if;
Stmt := DB.Create_Statement (Query);
Stmt.Bind_Param ("name", ADO.Parameters.Token (Name));
Stmt.Bind_Param ("user", ADO.Parameters.Token (User));
if Password'Length > 0 then
Stmt.Bind_Param ("password", Password);
end if;
Stmt.Execute;
Query.Set_Query (Gen.Database.Model.Query_Flush_Privileges);
Stmt := DB.Create_Statement (Query);
Stmt.Execute;
end Create_User_Grant;
-- ------------------------------
-- Execute the external command <b>Name</b> with the arguments in <b>Args</b>
-- and send the content of the file <b>Input</b> to that command.
-- ------------------------------
procedure Execute_Command (Command : in String;
Input : in String) is
Proc : aliased Util.Streams.Pipes.Pipe_Stream;
Text : Util.Streams.Texts.Reader_Stream;
begin
if Input /= "" then
Proc.Set_Input_Stream (Input);
end if;
Text.Initialize (Proc'Unchecked_Access);
Proc.Open (Command, Util.Processes.READ);
while not Text.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Text.Read_Line (Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Error ("{0}", Ada.Strings.Unbounded.To_String (Line));
end;
end loop;
Proc.Close;
if Proc.Get_Exit_Status = 0 then
Log.Info ("Database schema created successfully.");
elsif Proc.Get_Exit_Status = 255 then
Log.Error ("Command not found: {0}", Command);
else
Log.Error ("Command {0} failed with exit code {1}", Command,
Util.Strings.Image (Proc.Get_Exit_Status));
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read {0}", Input);
end Execute_Command;
-- ------------------------------
-- Create the MySQL tables in the database. The tables are created by launching
-- the external command 'mysql' and using the create-xxx-mysql.sql generated scripts.
-- ------------------------------
procedure Create_Mysql_Tables (Name : in String;
Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Generator : in out Gen.Generator.Handler) is
Database : constant String := Config.Get_Database;
Username : constant String := Config.Get_Property ("user");
Password : constant String := Config.Get_Property ("password");
Dir : constant String := Util.Files.Compose (Model, "mysql");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-mysql.sql");
begin
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
if Password'Length > 0 then
Execute_Command ("mysql --user=" & Username & " --password=" & Password & " "
& Database, File);
else
Execute_Command ("mysql --user=" & Username & " "
& Database, File);
end if;
end Create_Mysql_Tables;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name);
use Ada.Strings.Unbounded;
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String);
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String;
Username : in String;
Password : in String);
procedure Create_SQLite_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String);
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_MySQL_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String;
Username : in String;
Password : in String) is
Factory : ADO.Sessions.Factory.Session_Factory;
Root_Connection : Unbounded_String;
Root_Hidden : Unbounded_String;
Pos : Natural;
begin
-- Build a connection string to create the database.
Pos := Util.Strings.Index (Database, ':');
Append (Root_Connection, Database (Database'First .. Pos));
Append (Root_Connection, "//");
Append (Root_Connection, Config.Get_Server);
if Config.Get_Port > 0 then
Append (Root_Connection, ':');
Append (Root_Connection, Util.Strings.Image (Config.Get_Port));
end if;
Append (Root_Connection, "/?user=");
Append (Root_Connection, Username);
Root_Hidden := Root_Connection;
if Password'Length > 0 then
Append (Root_Connection, "&password=");
Root_Hidden := Root_Connection;
Append (Root_Connection, Password);
Append (Root_Hidden, "XXXXXXXX");
end if;
Log.Info ("Connecting to {0} for database setup", Root_Hidden);
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Factory.Create (To_String (Root_Connection));
declare
Name : constant String := Generator.Get_Project_Name;
DB : constant ADO.Sessions.Master_Session := Factory.Get_Master_Session;
begin
-- Create the database only if it does not already exists.
if not Has_Database (DB, Config.Get_Database) then
Create_Database (DB, Config.Get_Database);
end if;
-- If some tables exist, don't try to create tables again.
-- We could improve by reading the current database schema, comparing with our
-- schema and create what is missing (new tables, new columns).
if Has_Tables (DB, Config.Get_Database) then
Generator.Error ("The database {0} exists", Config.Get_Database);
else
-- Create the user grant. On MySQL, it is safe to do this several times.
Create_User_Grant (DB, Config.Get_Database,
Config.Get_Property ("user"),
Config.Get_Property ("password"));
-- And now create the tables by using the SQL script generated by Dyanmo.
Create_Mysql_Tables (Name, Model, Config, Generator);
end if;
end;
end Create_MySQL_Database;
-- ------------------------------
-- Create the SQLite database.
-- ------------------------------
procedure Create_SQLite_Database (Model : in String;
Config : in ADO.Drivers.Connections.Configuration;
Database : in String) is
Name : constant String := Generator.Get_Project_Name;
Path : constant String := Config.Get_Database;
Dir : constant String := Util.Files.Compose (Model, "sqlite");
File : constant String := Util.Files.Compose (Dir, "create-" & Name & "-sqlite.sql");
begin
if Ada.Directories.Exists (Path) then
Log.Info ("Connecting to {0} for database setup", Database);
end if;
-- Initialize the session factory to connect to the
-- database defined by root connection (which should allow the database creation).
Log.Info ("Creating database tables using schema '{0}'", File);
if not Ada.Directories.Exists (File) then
Generator.Error ("SQL file '{0}' does not exist.", File);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
Execute_Command ("sqlite3 --init " & File & " " & Path, "");
end Create_SQLite_Database;
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_Database (Model : in String;
Database : in String;
Username : in String;
Password : in String) is
Config : ADO.Drivers.Connections.Configuration;
begin
Config.Set_Connection (Database);
if Config.Get_Database = "" then
Generator.Error ("Invalid database connection: no database name specified");
return;
end if;
if Config.Get_Driver = "mysql" then
if Config.Get_Property ("user") = "" then
Generator.Error ("Invalid database connection: missing user property");
return;
end if;
Create_MySQL_Database (Model, Config, Database, Username, Password);
elsif Config.Get_Driver = "sqlite" then
Create_SQLite_Database (Model, Config, Database);
else
Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver);
end if;
-- Remember the database connection string.
Generator.Set_Project_Property ("database", Database);
Generator.Save_Project;
exception
when E : others =>
Generator.Error (Ada.Exceptions.Exception_Message (E));
end Create_Database;
Model : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else "");
Arg1 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else "");
Arg2 : constant String := (if Args.Get_Count > 2 then Args.Get_Argument (3) else "");
Arg3 : constant String := (if Args.Get_Count > 3 then Args.Get_Argument (4) else "");
begin
Generator.Read_Project ("dynamo.xml");
-- Initialize the database drivers.
ADO.Drivers.Initialize (Generator.Get_Properties);
-- Check if a database is specified in the command line and use it.
if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then
Create_Database (Model, Arg1, Arg2, Arg3);
else
declare
Database : constant String := Generator.Get_Project_Property ("database");
begin
-- Otherwise, get the database identification from dynamo.xml configuration.
if Ada.Strings.Fixed.Index (Database, "://") = 0 then
Generator.Error ("No database specified.");
return;
end if;
Create_Database (Model, Database, Arg1, Arg2);
end;
end if;
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-database: Creates the database");
Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]");
New_Line;
Put_Line (" Create the database specified by the connection string.");
Put_Line (" The connection string has the form:");
Put_Line (" driver://host[:port]/database");
New_Line;
Put_Line (" The database must not exist. The user specified in the connection string");
Put_Line (" is granted the access to the new database.");
end Help;
end Gen.Commands.Database;
|
Fix the database connection string
|
Fix the database connection string
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
4d5fba7eb890124b4b91115499f206fe59aa273c
|
regtests/security-permissions-tests.ads
|
regtests/security-permissions-tests.ads
|
-----------------------------------------------------------------------
-- Security-permissions-tests - Unit tests for Security.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 Util.Tests;
package Security.Permissions.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test Add_Permission and Get_Permission_Index
procedure Test_Add_Permission (T : in out Test);
end Security.Permissions.Tests;
|
-----------------------------------------------------------------------
-- Security-permissions-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Security.Permissions.Tests is
package P_Admin is new Permissions.Definition ("admin");
package P_Create is new Permissions.Definition ("create");
package P_Update is new Permissions.Definition ("update");
package P_Delete is new Permissions.Definition ("delete");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test Add_Permission and Get_Permission_Index
procedure Test_Add_Permission (T : in out Test);
-- Test the permission created by the Definition package.
procedure Test_Define_Permission (T : in out Test);
-- Test Get_Permission on invalid permission name.
procedure Test_Get_Invalid_Permission (T : in out Test);
end Security.Permissions.Tests;
|
Add new unit tests to check the Permissions.Definition package
|
Add new unit tests to check the Permissions.Definition package
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
f388fa078726275e0d24a53d741047dff9565d95
|
src/gen-commands-distrib.ads
|
src/gen-commands-distrib.ads
|
-----------------------------------------------------------------------
-- gen-commands-distrib -- Distrib command for dynamo
-- Copyright (C) 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.
-----------------------------------------------------------------------
package Gen.Commands.Distrib is
-- ------------------------------
-- Distrib Command
-- ------------------------------
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out 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 out Command;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Distrib;
|
-----------------------------------------------------------------------
-- gen-commands-distrib -- Distrib command for dynamo
-- Copyright (C) 2012, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Gen.Commands.Distrib is
-- ------------------------------
-- Distrib Command
-- ------------------------------
type Command is new Gen.Commands.Command with null record;
-- Execute the command with the arguments.
overriding
procedure Execute (Cmd : in out 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 out Command;
Name : in String;
Generator : in out Gen.Generator.Handler);
end Gen.Commands.Distrib;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
fc8df6e7addbacbcb3967d7343bc3852a8ada04b
|
src/babel-files-maps.adb
|
src/babel-files-maps.adb
|
-----------------------------------------------------------------------
-- babel-files-maps -- Hash maps for files and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Babel.Files.Maps is
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
procedure Add_File (Into : in out Differential_Container;
Element : in File_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
procedure Add_Directory (Into : in out Differential_Container;
Element : in Directory_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
function Create (Into : in Differential_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
function Create (Into : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
function Find (From : in Differential_Container;
Name : in String) return File_Type is
begin
return Find (From.Known_Files, Name);
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
function Find (From : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Find (From.Known_Dirs, Name);
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
overriding
procedure Set_Directory (Into : in out Differential_Container;
Directory : in Directory_Type) is
begin
Default_Container (Into).Set_Directory (Directory);
Into.Known_Files.Clear;
Into.Known_Dirs.Clear;
end Set_Directory;
end Babel.Files.Maps;
|
-----------------------------------------------------------------------
-- babel-files-maps -- Hash maps for files and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Babel.Files.Maps is
-- ------------------------------
-- Find the file with the given name in the file map.
-- ------------------------------
function Find (From : in File_Map;
Name : in String) return File_Cursor is
begin
return From.Find (Key => Name'Unrestricted_Access);
end Find;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
procedure Add_File (Into : in out Differential_Container;
Element : in File_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Files.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
procedure Add_Directory (Into : in out Differential_Container;
Element : in Directory_Type) is
use type ADO.Identifier;
begin
if Element.Id = ADO.NO_IDENTIFIER then
Into.Known_Dirs.Insert (Element.Name'Unrestricted_Access, Element);
end if;
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
function Create (Into : in Differential_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
function Create (Into : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
function Find (From : in Differential_Container;
Name : in String) return File_Type is
begin
return Find (From.Known_Files, Name);
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
function Find (From : in Differential_Container;
Name : in String) return Directory_Type is
begin
return Find (From.Known_Dirs, Name);
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
overriding
procedure Set_Directory (Into : in out Differential_Container;
Directory : in Directory_Type) is
begin
Default_Container (Into).Set_Directory (Directory);
Into.Known_Files.Clear;
Into.Known_Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Prepare the differential container by setting up the known files and known
-- directories. The <tt>Update</tt> procedure is called to give access to the
-- maps that can be updated.
-- ------------------------------
procedure Prepare (Container : in out Differential_Container;
Update : access procedure (Files : in out File_Map;
Dirs : in out Directory_Map)) is
begin
Update (Container.Known_Files, Container.Known_Dirs);
end Prepare;
end Babel.Files.Maps;
|
Implement the Prepare operation
|
Implement the Prepare operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
532da1482cc5e3ac0fb597aa641580948acf7d4f
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
end Babel.Files;
|
Implement the Allocate function to allocate a Directory_Type instance
|
Implement the Allocate function to allocate a Directory_Type instance
|
Ada
|
apache-2.0
|
stcarrez/babel
|
463476e56c39b72ae8293afbbf6d63d0ea81b82c
|
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 := "27";
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.28";
default_pgsql : constant String := "10";
default_php : constant String := "7.2";
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/pkg-static";
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 := "28";
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.28";
default_pgsql : constant String := "10";
default_php : constant String := "7.2";
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/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
bump version
|
bump version
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
bce64cbd19dfc1e4f4cacc6ce00979bfbb4d0729
|
src/util-listeners.ads
|
src/util-listeners.ads
|
-----------------------------------------------------------------------
-- util-listeners -- Listeners
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Concurrent.Arrays;
-- == Introduction ==
-- The `Listeners` package implements a simple observer/listener design pattern.
-- A subscriber registers to a list. When a change is made on an object, the
-- application can notify the subscribers which are then called with the object.
--
-- == Creating the listener list ==
-- The listeners list contains a list of listener interfaces.
--
-- L : Util.Listeners.List;
--
-- The list is heterogeneous meaning that several kinds of listeners could
-- be registered.
--
-- == Creating the observers ==
-- First the `Observers` package must be instantiated with the type being
-- observed. In the example below, we will observe a string:
--
-- package String_Observers is new Util.Listeners.Observers (String);
--
-- == Implementing the observer ==
-- Now we must implement the string observer:
--
-- type String_Observer is new String_Observer.Observer with null record;
-- procedure Update (List : in String_Observer; Item : in String);
--
-- == Registering the observer ==
-- An instance of the string observer must now be registered in the list.
--
-- O : aliased String_Observer;
-- L.Append (O'Access);
--
-- == Publishing ==
-- Notifying the listeners is done by invoking the `Notify` operation
-- provided by the `String_Observers` package:
--
-- String_Observer.Notify (L, "Hello");
--
package Util.Listeners is
-- The listener root interface.
type Listener is limited interface;
type Listener_Access is access all Listener'Class;
-- The multi-task safe list of listeners.
package Listener_Arrays is new Util.Concurrent.Arrays (Listener_Access);
-- ------------------------------
-- List of listeners
-- ------------------------------
-- The `List` type is a list of listeners that have been registered and must be
-- called when a notification is sent. The list uses the concurrent arrays thus
-- allowing tasks to add or remove listeners while dispatching is also running.
type List is new Listener_Arrays.Vector with null record;
procedure Add_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Append;
procedure Remove_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Remove;
end Util.Listeners;
|
-----------------------------------------------------------------------
-- util-listeners -- Listeners
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Concurrent.Arrays;
-- == Introduction ==
-- The `Listeners` package implements a simple observer/listener design pattern.
-- A subscriber registers to a list. When a change is made on an object, the
-- application can notify the subscribers which are then called with the object.
--
-- == Creating the listener list ==
-- The listeners list contains a list of listener interfaces.
--
-- L : Util.Listeners.List;
--
-- The list is heterogeneous meaning that several kinds of listeners could
-- be registered.
--
-- == Creating the observers ==
-- First the `Observers` package must be instantiated with the type being
-- observed. In the example below, we will observe a string:
--
-- package String_Observers is new Util.Listeners.Observers (String);
--
-- == Implementing the observer ==
-- Now we must implement the string observer:
--
-- type String_Observer is new String_Observer.Observer with null record;
-- procedure Update (List : in String_Observer; Item : in String);
--
-- == Registering the observer ==
-- An instance of the string observer must now be registered in the list.
--
-- O : aliased String_Observer;
-- L.Append (O'Access);
--
-- == Publishing ==
-- Notifying the listeners is done by invoking the `Notify` operation
-- provided by the `String_Observers` package:
--
-- String_Observer.Notify (L, "Hello");
--
package Util.Listeners is
-- The listener root interface.
type Listener is limited interface;
type Listener_Access is access all Listener'Class;
-- The multi-task safe list of listeners.
package Listener_Arrays is new Util.Concurrent.Arrays (Listener_Access);
-- ------------------------------
-- List of listeners
-- ------------------------------
-- The `List` type is a list of listeners that have been registered and must be
-- called when a notification is sent. The list uses the concurrent arrays thus
-- allowing tasks to add or remove listeners while dispatching is also running.
subtype List is Listener_Arrays.Vector;
procedure Add_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Append;
procedure Remove_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Remove;
end Util.Listeners;
|
Make the List type a subtype of Listener_Arras.Vector
|
Make the List type a subtype of Listener_Arras.Vector
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
93b6eb65ef01de533e2bc222558ea139263c1911
|
src/security-auth-openid.ads
|
src/security-auth-openid.ads
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 2.0 Support
-- 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.
-----------------------------------------------------------------------
-- === OpenID Configuration ==
-- The Open ID provider needs the following configuration parameters:
--
-- openid.realm The OpenID realm parameter passed in the authentication URL.
-- openid.callback_url The OpenID return_to parameter.
--
private package Security.Auth.OpenID is
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is new Security.Auth.Manager with private;
-- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt>
-- and <tt>openid.callback_url</tt> parameters to configure the realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
type Manager is new Security.Auth.Manager with record
Return_To : Unbounded_String;
Realm : Unbounded_String;
end record;
end Security.Auth.OpenID;
|
-----------------------------------------------------------------------
-- security-openid -- OpenID 2.0 Support
-- 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.
-----------------------------------------------------------------------
-- === OpenID Configuration ==
-- The Open ID provider needs the following configuration parameters:
--
-- openid.realm The OpenID realm parameter passed in the authentication URL.
-- openid.callback_url The OpenID return_to parameter.
--
private package Security.Auth.OpenID is
-- ------------------------------
-- OpenID Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OpenID process.
type Manager is new Security.Auth.Manager with private;
-- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt>
-- and <tt>openid.callback_url</tt> parameters to configure the realm.
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID);
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the authentication result
procedure Verify_Discovered (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
-- Verify the signature part of the result
procedure Verify_Signature (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : in out Authentication);
-- Extract from the XRDS content the OpenID provider URI.
-- The default implementation is very basic as it returns the first <URI>
-- available in the stream without validating the XRDS document.
-- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found.
procedure Extract_XRDS (Realm : in out Manager;
Content : in String;
Result : out End_Point);
private
type Manager is new Security.Auth.Manager with record
Return_To : Unbounded_String;
Realm : Unbounded_String;
end record;
end Security.Auth.OpenID;
|
Rename Initialize parameter
|
Rename Initialize parameter
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
e25254dae6d8f719a25387282a4cc3956c3404f6
|
src/wiki-documents.adb
|
src/wiki-documents.adb
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
-- ------------------------------
-- 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) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Returns True if the current node is the root document node.
-- ------------------------------
function Is_Root_Node (Doc : in Document) return Boolean is
begin
return Doc.Current = null;
end Is_Root_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0));
Into.Using_TOC := True;
end case;
end Append;
-- ------------------------------
-- 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) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- 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) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- 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) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Level => Level, others => <>));
end Add_Blockquote;
-- 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) is
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Preformatted => Text, others => <>));
end Add_Preformatted;
-- ------------------------------
-- 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 Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref) is
begin
if Wiki.Nodes.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Documents is
use Wiki.Nodes;
-- ------------------------------
-- 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) is
Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START,
Len => 0,
Tag_Start => Tag,
Attributes => Attributes,
Children => null,
Parent => Into.Current);
begin
Append (Into, Node);
Into.Current := Node;
end Push_Node;
-- ------------------------------
-- Pop the HTML tag.
-- ------------------------------
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag) is
pragma Unreferenced (Tag);
begin
if From.Current /= null then
From.Current := From.Current.Parent;
end if;
end Pop_Node;
-- ------------------------------
-- Returns True if the current node is the root document node.
-- ------------------------------
function Is_Root_Node (Doc : in Document) return Boolean is
begin
return Doc.Current = null;
end Is_Root_Node;
-- ------------------------------
-- Append a section header at end of the document.
-- ------------------------------
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Append (Into, new Node_Type '(Kind => N_HEADER,
Len => Header'Length,
Header => Header,
Level => Level));
end Append;
-- ------------------------------
-- Append a node to the document.
-- ------------------------------
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access) is
begin
if Into.Current = null then
Append (Into.Nodes, Node);
else
Append (Into.Current, Node);
end if;
end Append;
-- ------------------------------
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
-- ------------------------------
procedure Append (Into : in out Document;
Kind : in Simple_Node_Kind) is
begin
case Kind is
when N_LINE_BREAK =>
Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0));
when N_HORIZONTAL_RULE =>
Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0));
when N_PARAGRAPH =>
Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0));
when N_TOC_DISPLAY =>
Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0));
Into.Using_TOC := True;
end case;
end Append;
-- ------------------------------
-- 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) is
begin
Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length,
Text => Text, Format => Format));
end Append;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length,
Title => Name, Link_Attr => Attributes));
end Add_Quote;
-- ------------------------------
-- 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) is
begin
if Ordered then
Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0,
Level => Level, others => <>));
else
Append (Into, new Node_Type '(Kind => N_LIST, Len => 0,
Level => Level, others => <>));
end if;
end Add_List_Item;
-- ------------------------------
-- 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) is
begin
Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0,
Level => Level, others => <>));
end Add_Blockquote;
-- 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) is
pragma Unreferenced (Format);
begin
Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length,
Preformatted => Text, others => <>));
end Add_Preformatted;
-- ------------------------------
-- 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 Node_Type)) is
begin
Iterate (Doc.Nodes, Process);
end Iterate;
-- ------------------------------
-- Returns True if the document is empty.
-- ------------------------------
function Is_Empty (Doc : in Document) return Boolean is
begin
return Wiki.Nodes.Is_Empty (Doc.Nodes);
end Is_Empty;
-- ------------------------------
-- Returns True if the document displays the table of contents by itself.
-- ------------------------------
function Is_Using_TOC (Doc : in Document) return Boolean is
begin
return Doc.Using_TOC;
end Is_Using_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref) is
begin
if Wiki.Nodes.Is_Empty (Doc.TOC) then
Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>));
end if;
TOC := Doc.TOC;
end Get_TOC;
-- ------------------------------
-- Get the table of content node associated with the document.
-- ------------------------------
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is
begin
return Doc.TOC;
end Get_TOC;
end Wiki.Documents;
|
Fix compilation warnings (style)
|
Fix compilation warnings (style)
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
8ab3fc258b1c2669139a31c3e9946686ecae05e2
|
src/mysql/ado-drivers-connections-mysql.adb
|
src/mysql/ado-drivers-connections-mysql.adb
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Identification;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.Statements.Mysql;
with ADO.C;
with Mysql.Lib; use Mysql.Lib;
package body ADO.Drivers.Connections.Mysql is
use ADO.Statements.Mysql;
use Util.Log;
use Interfaces.C;
pragma Linker_Options (MYSQL_LIB_NAME);
Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql");
Driver_Name : aliased constant String := "mysql";
Driver : aliased Mysql_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return ADO.Drivers.Connections.Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create query statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create query statement {0}: connection is closed",
Query);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create delete statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create insert statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create update statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Autocommit then
Database.Execute ("set autocommit=0");
Database.Autocommit := False;
end if;
Database.Execute ("start transaction;");
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_commit (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot commit transaction";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_rollback (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot rollback transaction";
end if;
end Rollback;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
null;
end Load_Schema;
-- ------------------------------
-- Execute a simple SQL statement
-- ------------------------------
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
begin
Log.Debug ("Execute SQL: {0}", SQL);
if Database.Server = null then
Log.Error ("Database connection is not open");
raise Connection_Error with "Database connection is closed";
end if;
Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat));
Log.Debug ("Query result: {0}", int'Image (Result));
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
if Database.Server /= null then
Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident);
mysql_close (Database.Server);
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the mysql connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident);
Database.Close;
end Finalize;
-- ------------------------------
-- Initialize the database connection manager.
--
-- mysql://localhost:3306/db
--
-- ------------------------------
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : out ADO.Drivers.Connections.Database_Connection_Access) is
Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server);
Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database);
Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user"));
Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password"));
Socket : ADO.C.String_Ptr;
Port : unsigned := unsigned (Config.Port);
Flags : constant unsigned_long := 0;
Connection : Mysql_Access;
Socket_Path : constant String := Config.Get_Property ("socket");
Server : Mysql_Access;
begin
if Socket_Path /= "" then
ADO.C.Set_String (Socket, Socket_Path);
end if;
if Port = 0 then
Port := 3306;
end if;
Log.Info ("Task {0} connecting to {1}:{2}",
Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task),
To_String (Config.Server), To_String (Config.Database));
Log.Debug ("user={0} password={1}", Config.Get_Property ("user"),
Config.Get_Property ("password"));
Connection := mysql_init (null);
Server := mysql_real_connect (Connection, ADO.C.To_C (Host),
ADO.C.To_C (Login), ADO.C.To_C (Password),
ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags);
if Server = null then
declare
Message : constant String := Strings.Value (Mysql_Error (Connection));
begin
Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message);
mysql_close (Connection);
raise Connection_Error with "Cannot connect to mysql server: " & Message;
end;
end if;
D.Id := D.Id + 1;
declare
Ident : constant String := Util.Strings.Image (D.Id);
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name, Item : in Util.Properties.Value);
procedure Configure (Name, Item : in Util.Properties.Value) is
Value : constant String := To_String (Item);
begin
if Name = "encoding" then
Database.Execute ("SET NAMES " & Value);
Database.Execute ("SET CHARACTER SET " & Value);
Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'");
Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'");
elsif Name /= "user" and Name /= "password" then
Database.Execute ("SET " & To_String (Name) & "='" & Value & "'");
end if;
end Configure;
begin
Database.Ident (1 .. Ident'Length) := Ident;
Database.Server := Server;
Database.Count := 1;
Database.Name := Config.Database;
-- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands.
-- Typical configuration includes:
-- encoding=utf8
-- collation_connection=utf8_general_ci
Config.Properties.Iterate (Process => Configure'Access);
Result := Database.all'Access;
end;
end Create_Connection;
-- ------------------------------
-- Initialize the Mysql driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing mysql driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the Mysql driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Mysql_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the mysql driver");
mysql_server_end;
end Finalize;
end ADO.Drivers.Connections.Mysql;
|
-----------------------------------------------------------------------
-- ADO Mysql Database -- MySQL Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Identification;
with Interfaces.C.Strings;
with Util.Log;
with Util.Log.Loggers;
with ADO.Statements.Mysql;
with ADO.Schemas.Mysql;
with ADO.C;
with Mysql.Lib; use Mysql.Lib;
package body ADO.Drivers.Connections.Mysql is
use ADO.Statements.Mysql;
use Util.Log;
use Interfaces.C;
pragma Linker_Options (MYSQL_LIB_NAME);
Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql");
Driver_Name : aliased constant String := "mysql";
Driver : aliased Mysql_Driver;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
overriding
function Get_Driver (Database : in Database_Connection)
return ADO.Drivers.Connections.Driver_Access is
pragma Unreferenced (Database);
begin
return Driver'Access;
end Get_Driver;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create query statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create query statement {0}: connection is closed",
Query);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Query => Query);
end Create_Statement;
-- ------------------------------
-- Create a delete statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create delete statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an insert statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create insert statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Create an update statement.
-- ------------------------------
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is
begin
if Database.Server = null then
Log.Warn ("Cannot create update statement on table {0}: connection is closed",
Table.Table.all);
raise Connection_Error with "Database connection is closed";
end if;
return Create_Statement (Database => Database.Server, Table => Table);
end Create_Statement;
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Database_Connection) is
begin
if Database.Autocommit then
Database.Execute ("set autocommit=0");
Database.Autocommit := False;
end if;
Database.Execute ("start transaction;");
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_commit (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot commit transaction";
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Database_Connection) is
Result : char;
begin
Result := mysql_rollback (Database.Server);
if Result /= nul then
raise DB_Error with "Cannot rollback transaction";
end if;
end Rollback;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is
begin
ADO.Schemas.Mysql.Load_Schema (Database, Schema);
end Load_Schema;
-- ------------------------------
-- Execute a simple SQL statement
-- ------------------------------
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String) is
SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL);
Result : int;
begin
Log.Debug ("Execute SQL: {0}", SQL);
if Database.Server = null then
Log.Error ("Database connection is not open");
raise Connection_Error with "Database connection is closed";
end if;
Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat));
Log.Debug ("Query result: {0}", int'Image (Result));
end Execute;
-- ------------------------------
-- Closes the database connection
-- ------------------------------
overriding
procedure Close (Database : in out Database_Connection) is
begin
if Database.Server /= null then
Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident);
mysql_close (Database.Server);
Database.Server := null;
end if;
end Close;
-- ------------------------------
-- Releases the mysql connection if it is open
-- ------------------------------
overriding
procedure Finalize (Database : in out Database_Connection) is
begin
Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident);
Database.Close;
end Finalize;
-- ------------------------------
-- Initialize the database connection manager.
--
-- mysql://localhost:3306/db
--
-- ------------------------------
procedure Create_Connection (D : in out Mysql_Driver;
Config : in Configuration'Class;
Result : out ADO.Drivers.Connections.Database_Connection_Access) is
Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server);
Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database);
Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user"));
Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password"));
Socket : ADO.C.String_Ptr;
Port : unsigned := unsigned (Config.Port);
Flags : constant unsigned_long := 0;
Connection : Mysql_Access;
Socket_Path : constant String := Config.Get_Property ("socket");
Server : Mysql_Access;
begin
if Socket_Path /= "" then
ADO.C.Set_String (Socket, Socket_Path);
end if;
if Port = 0 then
Port := 3306;
end if;
Log.Info ("Task {0} connecting to {1}:{2}",
Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task),
To_String (Config.Server), To_String (Config.Database));
Log.Debug ("user={0} password={1}", Config.Get_Property ("user"),
Config.Get_Property ("password"));
Connection := mysql_init (null);
Server := mysql_real_connect (Connection, ADO.C.To_C (Host),
ADO.C.To_C (Login), ADO.C.To_C (Password),
ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags);
if Server = null then
declare
Message : constant String := Strings.Value (Mysql_Error (Connection));
begin
Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message);
mysql_close (Connection);
raise Connection_Error with "Cannot connect to mysql server: " & Message;
end;
end if;
D.Id := D.Id + 1;
declare
Ident : constant String := Util.Strings.Image (D.Id);
Database : constant Database_Connection_Access := new Database_Connection;
procedure Configure (Name, Item : in Util.Properties.Value);
procedure Configure (Name, Item : in Util.Properties.Value) is
Value : constant String := To_String (Item);
begin
if Name = "encoding" then
Database.Execute ("SET NAMES " & Value);
Database.Execute ("SET CHARACTER SET " & Value);
Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'");
Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'");
elsif Name /= "user" and Name /= "password" then
Database.Execute ("SET " & To_String (Name) & "='" & Value & "'");
end if;
end Configure;
begin
Database.Ident (1 .. Ident'Length) := Ident;
Database.Server := Server;
Database.Count := 1;
Database.Name := Config.Database;
-- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands.
-- Typical configuration includes:
-- encoding=utf8
-- collation_connection=utf8_general_ci
Config.Properties.Iterate (Process => Configure'Access);
Result := Database.all'Access;
end;
end Create_Connection;
-- ------------------------------
-- Initialize the Mysql driver.
-- ------------------------------
procedure Initialize is
use type Util.Strings.Name_Access;
begin
Log.Debug ("Initializing mysql driver");
if Driver.Name = null then
Driver.Name := Driver_Name'Access;
Register (Driver'Access);
end if;
end Initialize;
-- ------------------------------
-- Deletes the Mysql driver.
-- ------------------------------
overriding
procedure Finalize (D : in out Mysql_Driver) is
pragma Unreferenced (D);
begin
Log.Debug ("Deleting the mysql driver");
mysql_server_end;
end Finalize;
end ADO.Drivers.Connections.Mysql;
|
Implement the Load_Schema operation on the database connection driver
|
Implement the Load_Schema operation on the database connection driver
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
e8fd7d3b6320074d634b0a8982a4c42d74df76d1
|
regtests/util-properties-tests.adb
|
regtests/util-properties-tests.adb
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
procedure Test_Save_Properties (T : in out Test) is
begin
declare
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
Props.Set ("New-Property", "Some-Value");
Props.Remove ("mysqld");
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed");
Props.Save_Properties ("regtests/result/save-props.properties");
end;
declare
Props : Properties.Manager;
V : Util.Properties.Value;
P : Properties.Manager;
begin
Props.Load_Properties (Path => "regtests/result/save-props.properties");
T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)");
T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
end Test_Save_Properties;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties",
Test_Save_Properties'Access);
end Add_Tests;
end Util.Properties.Tests;
|
Add test for Save_Properties
|
Add test for Save_Properties
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
870cbdf49af4e068dc3a4eced633d31a86e54430
|
src/wiki-filters-html.ads
|
src/wiki-filters-html.ads
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Containers.Vectors;
-- === HTML Filters ===
-- The <b>Wiki.Filters.Html</b> package implements a customizable HTML filter that verifies
-- the HTML content embedded in the Wiki text.
--
-- The HTML filter may be declared and configured as follows:
--
-- F : aliased Wiki.Filters.Html.Html_Filter_Type;
-- ...
-- F.Forbidden (Wiki.Filters.Html.SCRIPT_TAG);
-- F.Forbidden (Wiki.Filters.Html.A_TAG);
--
-- The <tt>Set_Document</tt> operation is used to link the HTML filter to a next filter
-- or to the HTML or text renderer:
--
-- F.Set_Document (Renderer'Access);
--
-- The HTML filter is then either inserted as a document for a previous filter or for
-- the wiki parser:
--
-- Wiki.Parsers.Parse (F'Access, Wiki_Text, Syntax);
--
package Wiki.Filters.Html is
-- ------------------------------
-- Filter type
-- ------------------------------
type Html_Filter_Type is new Filter_Type with private;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a link.
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document);
-- Mark the HTML tag as being forbidden.
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being allowed.
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being visible.
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Flush the HTML element that have not yet been closed.
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document);
private
use Wiki.Nodes;
type Tag_Boolean_Array is array (Html_Tag) of Boolean;
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Html_Tag);
subtype Tag_Vector is Tag_Vectors.Vector;
subtype Tag_Cursor is Tag_Vectors.Cursor;
type Html_Filter_Type is new Filter_Type with record
Allowed : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => False,
ROOT_HTML_TAG => False,
HEAD_TAG => False,
BODY_TAG => False,
META_TAG => False,
TITLE_TAG => False,
others => True);
Hidden : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => True,
STYLE_TAG => True,
others => False);
Stack : Tag_Vector;
Hide_Level : Natural := 0;
end record;
end Wiki.Filters.Html;
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Containers.Vectors;
-- === HTML Filters ===
-- The <b>Wiki.Filters.Html</b> package implements a customizable HTML filter that verifies
-- the HTML content embedded in the Wiki text.
--
-- The HTML filter may be declared and configured as follows:
--
-- F : aliased Wiki.Filters.Html.Html_Filter_Type;
-- ...
-- F.Forbidden (Wiki.Filters.Html.SCRIPT_TAG);
-- F.Forbidden (Wiki.Filters.Html.A_TAG);
--
-- The <tt>Set_Document</tt> operation is used to link the HTML filter to a next filter
-- or to the HTML or text renderer:
--
-- F.Set_Document (Renderer'Access);
--
-- The HTML filter is then either inserted as a document for a previous filter or for
-- the wiki parser:
--
-- Wiki.Parsers.Parse (F'Access, Wiki_Text, Syntax);
--
package Wiki.Filters.Html is
-- ------------------------------
-- Filter type
-- ------------------------------
type Html_Filter_Type is new Filter_Type with private;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a link.
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document);
-- Mark the HTML tag as being forbidden.
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being allowed.
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being visible.
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Flush the HTML element that have not yet been closed.
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document);
private
use Wiki.Nodes;
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Html_Tag);
subtype Tag_Vector is Tag_Vectors.Vector;
subtype Tag_Cursor is Tag_Vectors.Cursor;
type Html_Filter_Type is new Filter_Type with record
Allowed : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => False,
ROOT_HTML_TAG => False,
HEAD_TAG => False,
BODY_TAG => False,
META_TAG => False,
TITLE_TAG => False,
others => True);
Hidden : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => True,
STYLE_TAG => True,
others => False);
Stack : Tag_Vector;
Hide_Level : Natural := 0;
end record;
end Wiki.Filters.Html;
|
Move the Tag_Boolean_Array, Tag_Omission, No_End_Tag to the Wiki package
|
Move the Tag_Boolean_Array, Tag_Omission, No_End_Tag to the Wiki package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
2ab8f73a59b049ac8e737a3a852091927370e31d
|
src/ado-sessions-factory.ads
|
src/ado-sessions-factory.ads
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- with Ada.Finalization;
with ADO.Databases;
with ADO.Schemas.Entities;
with ADO.Sequences;
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
package ADO.Sessions.Factory is
pragma Elaborate_Body;
-- ------------------------------
-- Session factory
-- ------------------------------
type Session_Factory is tagged limited private;
type Session_Factory_Access is access all Session_Factory'Class;
-- Get a read-only session from the factory.
function Get_Session (Factory : in Session_Factory) return Session;
-- Get a read-write session from the factory.
function Get_Master_Session (Factory : in Session_Factory) return Master_Session;
-- Open a session
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session);
-- Open a session
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session);
-- Create the session factory to connect to the database represented
-- by the data source.
procedure Create (Factory : out Session_Factory;
Source : in ADO.Databases.DataSource);
-- Create the session factory to connect to the database identified
-- by the URI.
procedure Create (Factory : out Session_Factory;
URI : in String);
-- 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_Proxy_Access) return Session;
function Get_Session (Proxy : in Session_Record_Access) return Session;
private
-- The session factory holds the necessary information to obtain a master or slave
-- database connection. The sequence factory is shared by all sessions of the same
-- factory (implementation is thread-safe). The factory also contains the entity type
-- cache which is initialized when the factory is created.
type Session_Factory is tagged limited record -- new Ada.Finalization.Limited_Controlled with record
Source : ADO.Databases.DataSource;
Sequences : Factory_Access := null;
Seq_Factory : aliased ADO.Sequences.Factory;
Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache;
Entities : ADO.Sessions.Entity_Cache_Access := null;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Databases;
with ADO.Schemas.Entities;
with ADO.Sequences;
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
package ADO.Sessions.Factory is
pragma Elaborate_Body;
-- ------------------------------
-- Session factory
-- ------------------------------
type Session_Factory is tagged limited private;
type Session_Factory_Access is access all Session_Factory'Class;
-- Get a read-only session from the factory.
function Get_Session (Factory : in Session_Factory) return Session;
-- Get a read-write session from the factory.
function Get_Master_Session (Factory : in Session_Factory) return Master_Session;
-- Open a session
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session);
-- Open a session
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session);
-- Create the session factory to connect to the database represented
-- by the data source.
procedure Create (Factory : out Session_Factory;
Source : in ADO.Databases.DataSource);
-- Create the session factory to connect to the database identified
-- by the URI.
procedure Create (Factory : out Session_Factory;
URI : in String);
-- 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_Proxy_Access) return Session;
function Get_Session (Proxy : in Session_Record_Access) return Session;
private
-- The session factory holds the necessary information to obtain a master or slave
-- database connection. The sequence factory is shared by all sessions of the same
-- factory (implementation is thread-safe). The factory also contains the entity type
-- cache which is initialized when the factory is created.
type Session_Factory is tagged limited record
Source : ADO.Databases.DataSource;
Sequences : Factory_Access := null;
Seq_Factory : aliased ADO.Sequences.Factory;
Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache;
Entities : ADO.Sessions.Entity_Cache_Access := null;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
ba89abb45a2313025b7073e2e0f2408efedca99c
|
src/asf-security-filters.adb
|
src/asf-security-filters.adb
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- 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.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Permission_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Permissions.Permission_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Permissions;
use type ASF.Principals.Principal_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URI : constant String := Request.Get_Path_Info;
Perm : constant URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
if not F.Manager.Has_Permission (Context'Unchecked_Access, Perm) then
Log.Info ("Deny access on {0}", URI);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- 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.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.Urls;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.Urls;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URI : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URI);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
Fix compilation for the new Security package
|
Fix compilation for the new Security package
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
13e4be882d66dc0ff45736f1bc35e5c467c8c2cb
|
src/gen-commands-project.adb
|
src/gen-commands-project.adb
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- 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 Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
Gtk_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: ? -web -tool -ado -gtk") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
elsif Full_Switch = "-gtk" then
Gtk_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag));
Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag));
Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag));
Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag));
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
if Ado_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado");
elsif Gtk_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk");
else
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
end if;
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|mit|bsd3|proprietary] [--web] [--tool]"
& "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses");
Put_Line (" license, the GNU license or a proprietary license.");
Put_Line (" The author's name and email addresses are also reported in generated files.");
New_Line;
Put_Line (" --web Generate a Web application (the default)");
Put_Line (" --tool Generate a command line tool");
Put_Line (" --ado Generate a database tool operation for ADO");
Put_Line (" --gtk Generate a GtkAda project");
end Help;
end Gen.Commands.Project;
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- 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 Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
Gtk_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: ? -web -tool -ado -gtk") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
elsif Full_Switch = "-gtk" then
Gtk_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag));
Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag));
Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag));
Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag));
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
if Ado_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado");
elsif Gtk_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk");
else
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
end if;
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]"
& "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses");
Put_Line (" license, the GNU licenses or a proprietary license.");
Put_Line (" The author's name and email addresses are also reported in generated files.");
New_Line;
Put_Line (" --web Generate a Web application (the default)");
Put_Line (" --tool Generate a command line tool");
Put_Line (" --ado Generate a database tool operation for ADO");
Put_Line (" --gtk Generate a GtkAda project");
end Help;
end Gen.Commands.Project;
|
Add support for GPL v3 license
|
Add support for GPL v3 license
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
4c3cb539632372006de8c06a9cbca174b20aca75
|
src/gen-commands-propset.adb
|
src/gen-commands-propset.adb
|
-----------------------------------------------------------------------
-- gen-commands-propset -- Set a property on dynamo project
-- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
package body Gen.Commands.Propset is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
begin
if Args.Get_Count /= 2 then
Cmd.Usage (Name);
return;
end if;
Generator.Read_Project ("dynamo.xml", True);
Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2));
Generator.Save_Project;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("propset: Set the value of a property in the dynamo project file");
Put_Line ("Usage: propset NAME VALUE");
New_Line;
end Help;
end Gen.Commands.Propset;
|
-----------------------------------------------------------------------
-- gen-commands-propset -- Set a property on dynamo project
-- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
package body Gen.Commands.Propset is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
begin
if Args.Get_Count /= 2 then
Cmd.Usage (Name, Generator);
return;
end if;
Generator.Read_Project ("dynamo.xml", True);
Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2));
Generator.Save_Project;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("propset: Set the value of a property in the dynamo project file");
Put_Line ("Usage: propset NAME VALUE");
New_Line;
end Help;
end Gen.Commands.Propset;
|
Update to use an in out parameter for Help procedure
|
Update to use an in out parameter for Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3d26ea69742a67afad9e119ddf6561ad5ea30925
|
src/asf-security-filters-oauth.adb
|
src/asf-security-filters-oauth.adb
|
-----------------------------------------------------------------------
-- security-filters-oauth -- OAuth Security filter
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.URLs;
package body ASF.Security.Filters.OAuth is
use Ada.Strings.Unbounded;
use Servers;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Filters.OAuth");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config) is
use ASF.Applications;
Context : constant Servlets.Servlet_Registry_Access := Servlets.Get_Servlet_Context (Config);
begin
if Context.all in Main.Application'Class then
Server.Set_Permission_Manager (Main.Application'Class (Context.all).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
function Get_Access_Token (Request : in ASF.Requests.Request'Class) return String is
Header : constant String := Request.Get_Header (AUTHORIZATION_HEADER_NAME);
begin
if Header'Length > 0 then
return Header;
end if;
return Header;
end Get_Access_Token;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Servlet : constant String := Request.Get_Servlet_Path;
URL : constant String := Servlet & Request.Get_Path_Info;
begin
if F.Realm = null then
Log.Error ("Deny access on {0} due to missing realm", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
declare
Bearer : constant String := Get_Access_Token (Request);
Auth : Principal_Access;
Grant : Servers.Grant_Type;
Context : aliased Contexts.Security_Context;
begin
if Bearer'Length = 0 then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
F.Realm.Authenticate (Bearer, Grant);
if Grant.Status /= Valid_Grant then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end;
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (Request);
begin
Response.Add_Header (WWW_AUTHENTICATE_HEADER_NAME,
"Bearer realm=""" & To_String (F.Realm_URL)
& """, error=""invalid_token""");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
end ASF.Security.Filters.OAuth;
|
-----------------------------------------------------------------------
-- security-filters-oauth -- OAuth Security filter
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.URLs;
package body ASF.Security.Filters.OAuth is
use Ada.Strings.Unbounded;
use Servers;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Filters.OAuth");
function Get_Access_Token (Request : in ASF.Requests.Request'Class) return String;
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config) is
use ASF.Applications;
Context : constant Servlets.Servlet_Registry_Access := Servlets.Get_Servlet_Context (Config);
begin
if Context.all in Main.Application'Class then
Server.Set_Permission_Manager (Main.Application'Class (Context.all).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
function Get_Access_Token (Request : in ASF.Requests.Request'Class) return String is
Header : constant String := Request.Get_Header (AUTHORIZATION_HEADER_NAME);
begin
if Header'Length > 0 then
return Header;
end if;
return Header;
end Get_Access_Token;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Policies.URLs;
use type Policies.Policy_Manager_Access;
Servlet : constant String := Request.Get_Servlet_Path;
URL : constant String := Servlet & Request.Get_Path_Info;
begin
if F.Realm = null then
Log.Error ("Deny access on {0} due to missing realm", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
declare
Bearer : constant String := Get_Access_Token (Request);
Auth : Principal_Access;
Grant : Servers.Grant_Type;
Context : aliased Contexts.Security_Context;
begin
if Bearer'Length = 0 then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
F.Realm.Authenticate (Bearer, Grant);
if Grant.Status /= Valid_Grant then
Log.Info ("Ask authentication on {0} due to missing access token", URL);
Auth_Filter'Class (F).Do_Deny (Request, Response);
return;
end if;
-- OAuth_Permission
-- if not F.Manager.Has_Permission (Context, Perm) then
-- -- deny
-- Request.Set_Attribute ("application", Grant.Application);
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end;
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (Request);
begin
Response.Add_Header (WWW_AUTHENTICATE_HEADER_NAME,
"Bearer realm=""" & To_String (F.Realm_URL)
& """, error=""invalid_token""");
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
end ASF.Security.Filters.OAuth;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
865f224f911bceed35696bc48ed1bd38e533abda
|
src/gen-commands-docs.adb
|
src/gen-commands-docs.adb
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- Copyright (C) 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 GNAT.Command_Line;
with Ada.Text_IO;
with Gen.Artifacts.Docs;
with Gen.Model.Packages;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Args);
Doc : Gen.Artifacts.Docs.Artifact;
M : Gen.Model.Packages.Model_Definition;
Arg1 : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Footer : Boolean := True;
Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE;
begin
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml", False);
end if;
if Arg1'Length = 0 then
Generator.Error ("Missing target directory");
return;
elsif Arg1 (Arg1'First) /= '-' then
if Arg2'Length /= 0 then
Generator.Error ("Invalid markup option " & Arg1);
return;
end if;
-- Setup the target directory where the distribution is created.
Generator.Set_Result_Directory (Arg1);
else
if Arg1 = "-markdown" then
Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN;
elsif Arg1 = "-google" then
Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE;
elsif Arg1 = "-pandoc" then
Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN;
Footer := False;
else
Generator.Error ("Invalid markup option " & Arg1);
return;
end if;
if Arg2'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Arg2);
end if;
Doc.Set_Format (Fmt, Footer);
Doc.Read_Links (Generator.Get_Project_Property ("links", "links.txt"));
Doc.Prepare (M, Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc [-markdown|-google|-pandoc] target-dir");
New_Line;
Put_Line (" Extract the documentation from the project source files and generate the");
Put_Line (" project documentation. The following files are scanned:");
Put_Line (" - Ada specifications (src/*.ads)");
Put_Line (" - XML configuration files (config/*.xml)");
Put_Line (" - XML database model files (db/*.xml)");
end Help;
end Gen.Commands.Docs;
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- Copyright (C) 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 GNAT.Command_Line;
with Ada.Text_IO;
with Ada.Directories;
with Gen.Artifacts.Docs;
with Gen.Model.Packages;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Args);
Doc : Gen.Artifacts.Docs.Artifact;
M : Gen.Model.Packages.Model_Definition;
Arg1 : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Footer : Boolean := True;
Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE;
begin
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml", False);
end if;
if Arg1'Length = 0 then
Generator.Error ("Missing target directory");
return;
elsif Arg1 (Arg1'First) /= '-' then
if Arg2'Length /= 0 then
Generator.Error ("Invalid markup option " & Arg1);
return;
end if;
-- Setup the target directory where the distribution is created.
Generator.Set_Result_Directory (Arg1);
else
if Arg1 = "-markdown" then
Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN;
elsif Arg1 = "-google" then
Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE;
elsif Arg1 = "-pandoc" then
Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN;
Footer := False;
else
Generator.Error ("Invalid markup option " & Arg1);
return;
end if;
if Arg2'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Arg2);
end if;
Doc.Set_Format (Fmt, Footer);
Doc.Read_Links (Generator.Get_Project_Property ("links", "links.txt"));
Doc.Prepare (M, Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc [-markdown|-google|-pandoc] target-dir");
New_Line;
Put_Line (" Extract the documentation from the project source files and generate the");
Put_Line (" project documentation. The following files are scanned:");
Put_Line (" - Ada specifications (src/*.ads)");
Put_Line (" - XML configuration files (config/*.xml)");
Put_Line (" - XML database model files (db/*.xml)");
end Help;
end Gen.Commands.Docs;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
638e30297b9eb4ba918f3d36f444e1c503b2e594
|
awa/plugins/awa-votes/src/awa-votes-modules.adb
|
awa/plugins/awa-votes/src/awa-votes-modules.adb
|
-----------------------------------------------------------------------
-- awa-votes-modules -- Module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.Permissions;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Votes.Beans;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Votes.Models;
with ADO.SQL;
with ADO.Sessions;
with ADO.Statements;
with ADO.Sessions.Entities;
package body AWA.Votes.Modules is
use AWA.Services;
use ADO.Sessions;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module");
package Register is new AWA.Modules.Beans (Module => Vote_Module,
Module_Access => Vote_Module_Access);
-- ------------------------------
-- Initialize the votes module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the votes module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Votes.Beans.Votes_Bean",
Handler => AWA.Votes.Beans.Create_Vote_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the votes module.
-- ------------------------------
function Get_Vote_Module return Vote_Module_Access is
function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME);
begin
return Get;
end Get_Vote_Module;
-- ------------------------------
-- Vote for the given element and return the total vote for that element.
-- ------------------------------
procedure Vote_For (Model : in Vote_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Value : in Integer;
Total : out Integer) is
pragma Unreferenced (Model);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
Rating : AWA.Votes.Models.Rating_Ref;
Vote : AWA.Votes.Models.Vote_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
begin
Log.Info ("User {0} votes for {1} rating {2}",
ADO.Identifier'Image (User.Get_Id), Ident,
Integer'Image (Value));
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
-- Check that the user has the vote permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
-- Get the vote associated with the object for the user.
Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id");
Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type "
& "and o.user_id = :user_id");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Query.Bind_Param ("user_id", User.Get_Id);
Vote.Find (DB, Query, Found);
if not Found then
-- If the rating is 0, do not create any vote.
if Value = 0 then
return;
end if;
Query.Clear;
-- Get the rating associated with the object.
Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Rating.Find (DB, Query, Found);
-- Create it if it does not exist.
if not Found then
Log.Info ("Creating rating for {0}", Ident);
Rating.Set_For_Entity_Id (Id);
Rating.Set_For_Entity_Type (Kind);
Rating.Set_Rating (Value);
Rating.Set_Vote_Count (1);
else
Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1);
Rating.Set_Rating (Value + Rating.Get_Rating);
end if;
Rating.Save (DB);
Vote.Set_User (User);
Vote.Set_Entity (Rating);
else
Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity);
Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating);
Rating.Save (DB);
end if;
Vote.Set_Rating (Value);
Vote.Save (DB);
-- Return the total rating for the element.
Total := Rating.Get_Rating;
Ctx.Commit;
end Vote_For;
end AWA.Votes.Modules;
|
-----------------------------------------------------------------------
-- awa-votes-modules -- Module votes
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Security.Permissions;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Votes.Beans;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Votes.Models;
with ADO.SQL;
with ADO.Sessions;
with ADO.Sessions.Entities;
package body AWA.Votes.Modules is
use AWA.Services;
use ADO.Sessions;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module");
package Register is new AWA.Modules.Beans (Module => Vote_Module,
Module_Access => Vote_Module_Access);
-- ------------------------------
-- Initialize the votes module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the votes module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Votes.Beans.Votes_Bean",
Handler => AWA.Votes.Beans.Create_Vote_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the votes module.
-- ------------------------------
function Get_Vote_Module return Vote_Module_Access is
function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME);
begin
return Get;
end Get_Vote_Module;
-- ------------------------------
-- Vote for the given element and return the total vote for that element.
-- ------------------------------
procedure Vote_For (Model : in Vote_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Value : in Integer;
Total : out Integer) is
pragma Unreferenced (Model);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
Rating : AWA.Votes.Models.Rating_Ref;
Vote : AWA.Votes.Models.Vote_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
begin
Log.Info ("User {0} votes for {1} rating {2}",
ADO.Identifier'Image (User.Get_Id), Ident,
Integer'Image (Value));
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
-- Check that the user has the vote permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
-- Get the vote associated with the object for the user.
Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id");
Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type "
& "and o.user_id = :user_id");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Query.Bind_Param ("user_id", User.Get_Id);
Vote.Find (DB, Query, Found);
if not Found then
Query.Clear;
-- Get the rating associated with the object.
Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Rating.Find (DB, Query, Found);
-- Create it if it does not exist.
if not Found then
Log.Info ("Creating rating for {0}", Ident);
Rating.Set_For_Entity_Id (Id);
Rating.Set_For_Entity_Type (Kind);
Rating.Set_Rating (Value);
Rating.Set_Vote_Count (1);
else
Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1);
Rating.Set_Rating (Value + Rating.Get_Rating);
end if;
Rating.Save (DB);
Vote.Set_User (User);
Vote.Set_Entity (Rating);
else
Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity);
Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating);
Rating.Save (DB);
end if;
Vote.Set_Rating (Value);
Vote.Save (DB);
-- Return the total rating for the element.
Total := Rating.Get_Rating;
Ctx.Commit;
end Vote_For;
end AWA.Votes.Modules;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
adbddfdaf9485376cc28758f60f6f09d8aec43b6
|
src/util-encoders-base16.ads
|
src/util-encoders-base16.ads
|
-----------------------------------------------------------------------
-- util-encoders-base16 -- Encode/Decode a stream in hexadecimal
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
-- The <b>Util.Encodes.Base16</b> packages encodes and decodes streams
-- in hexadecimal.
package Util.Encoders.Base16 is
pragma Preelaborate;
-- ------------------------------
-- Base16 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an ascii hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base16 (hexadecimal) output stream <b>Into</b>.
--
-- 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> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Encoder;
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);
-- ------------------------------
-- Base16 decoder
-- ------------------------------
-- The <b>Decoder</b> decodes an hexadecimal stream into a binary stream.
type Decoder is new Util.Encoders.Transformer with private;
-- Decodes the base16 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- 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> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Decoder;
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);
private
type Encoder is new Util.Encoders.Transformer with null record;
type Decoder is new Util.Encoders.Transformer with null record;
generic
type Input_Char is (<>);
type Output_Char is (<>);
type Index is range <>;
type Output_Index is range <>;
type Input is array (Index range <>) of Input_Char;
type Output is array (Output_Index range <>) of Output_Char;
package Encoding is
procedure Encode (From : in Input;
Into : in out Output;
Last : out Output_Index;
Encoded : out Index);
procedure Decode (From : in Input;
Into : in out Output;
Last : out Output_Index;
Encoded : out Index);
end Encoding;
end Util.Encoders.Base16;
|
-----------------------------------------------------------------------
-- util-encoders-base16 -- Encode/Decode a stream in hexadecimal
-- 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.
-----------------------------------------------------------------------
with Ada.Streams;
-- The <b>Util.Encodes.Base16</b> packages encodes and decodes streams
-- in hexadecimal.
package Util.Encoders.Base16 is
pragma Preelaborate;
-- ------------------------------
-- Base16 encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an ascii hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base16 (hexadecimal) output stream <b>Into</b>.
--
-- 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> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
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);
-- ------------------------------
-- Base16 decoder
-- ------------------------------
-- The <b>Decoder</b> decodes an hexadecimal stream into a binary stream.
type Decoder is new Util.Encoders.Transformer with private;
-- Decodes the base16 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- 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> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Decoder;
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);
private
type Encoder is new Util.Encoders.Transformer with null record;
type Decoder is new Util.Encoders.Transformer with null record;
generic
type Input_Char is (<>);
type Output_Char is (<>);
type Index is range <>;
type Output_Index is range <>;
type Input is array (Index range <>) of Input_Char;
type Output is array (Output_Index range <>) of Output_Char;
package Encoding is
procedure Encode (From : in Input;
Into : in out Output;
Last : out Output_Index;
Encoded : out Index);
procedure Decode (From : in Input;
Into : in out Output;
Last : out Output_Index;
Encoded : out Index);
end Encoding;
end Util.Encoders.Base16;
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
98ded3317acdb7eb9709976c893996820e273554
|
orka/src/gl/interface/gl-objects-framebuffers.ads
|
orka/src/gl/interface/gl-objects-framebuffers.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2013 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Buffers;
with GL.Low_Level.Enums;
with GL.Objects.Textures;
with GL.Pixels.Extensions;
with GL.Types.Colors;
private with GL.Enums;
package GL.Objects.Framebuffers is
pragma Preelaborate;
use all type GL.Low_Level.Enums.Texture_Kind;
type Framebuffer_Status is (Undefined, Complete, Incomplete_Attachment,
Incomplete_Missing_Attachment,
Incomplete_Draw_Buffer, Incomplete_Read_Buffer,
Unsupported, Incomplete_Multisample,
Incomplete_Layer_Targets);
type Attachment_Point is (Depth_Stencil_Attachment,
Color_Attachment_0, Color_Attachment_1,
Color_Attachment_2, Color_Attachment_3,
Color_Attachment_4, Color_Attachment_5,
Color_Attachment_6, Color_Attachment_7,
Color_Attachment_8, Color_Attachment_9,
Color_Attachment_10, Color_Attachment_11,
Color_Attachment_12, Color_Attachment_13,
Color_Attachment_14, Color_Attachment_15,
Depth_Attachment, Stencil_Attachment);
type Default_Attachment_Point is
(Front_Left, Front_Right, Back_Left, Back_Right, Depth, Stencil);
type Attachment_List is array (Positive range <>) of Attachment_Point;
type Default_Attachment_List is array (Positive range <>) of Default_Attachment_Point;
function Valid_Attachment
(Attachment : Attachment_Point;
Texture : Textures.Texture) return Boolean
with Pre => not Texture.Compressed and Texture.Allocated;
type Framebuffer is new GL_Object with private;
overriding
procedure Initialize_Id (Object : in out Framebuffer);
overriding
procedure Delete_Id (Object : in out Framebuffer);
overriding
function Identifier (Object : Framebuffer) return Types.Debug.Identifier is
(Types.Debug.Framebuffer);
procedure Set_Draw_Buffer
(Object : Framebuffer;
Selector : Buffers.Color_Buffer_Selector)
with Pre => (if Object = Default_Framebuffer then
Selector in Buffers.Default_Color_Buffer_Selector | Buffers.None
else
Selector in Buffers.Explicit_Color_Buffer_Selector | Buffers.None);
procedure Set_Draw_Buffers
(Object : Framebuffer;
List : Buffers.Color_Buffer_List)
with Pre => (if Object = Default_Framebuffer then
(for all S of List =>
S in Buffers.Default_Color_Buffer_Selector | Buffers.None)
else
(for all S of List =>
S in Buffers.Explicit_Color_Buffer_Selector | Buffers.None));
procedure Set_Read_Buffer (Object : Framebuffer; Selector : Buffers.Color_Buffer_Selector)
with Pre => (if Object = Default_Framebuffer then
Selector in Buffers.Default_Color_Buffer_Selector | Buffers.None
else
Selector in Buffers.Explicit_Color_Buffer_Selector | Buffers.None);
procedure Attach_Texture
(Object : Framebuffer;
Attachment : Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level)
with Pre => Object /= Default_Framebuffer and
Valid_Attachment (Attachment, Texture) and
(if Texture.Kind in
Texture_2D_Multisample | Texture_2D_Multisample_Array
then Level = 0);
procedure Attach_Texture_Layer
(Object : Framebuffer;
Attachment : Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level;
Layer : Natural)
with Pre => Object /= Default_Framebuffer and
Valid_Attachment (Attachment, Texture) and
Texture.Layered;
procedure Detach (Object : Framebuffer; Attachment : Attachment_Point)
with Pre => Object /= Default_Framebuffer;
procedure Invalidate_Data
(Object : Framebuffer;
Attachments : Attachment_List)
with Pre => Object /= Default_Framebuffer;
procedure Invalidate_Sub_Data
(Object : Framebuffer;
Attachments : Attachment_List;
X, Y : Int;
Width, Height : Size)
with Pre => Object /= Default_Framebuffer;
procedure Invalidate_Data
(Object : Framebuffer;
Attachments : Default_Attachment_List)
with Pre => Object = Default_Framebuffer;
procedure Invalidate_Sub_Data
(Object : Framebuffer;
Attachments : Default_Attachment_List;
X, Y : Int;
Width, Height : Size)
with Pre => Object = Default_Framebuffer;
procedure Set_Default_Width (Object : Framebuffer; Value : Size);
procedure Set_Default_Height (Object : Framebuffer; Value : Size);
procedure Set_Default_Layers (Object : Framebuffer; Value : Size);
procedure Set_Default_Samples (Object : Framebuffer; Value : Size);
procedure Set_Default_Fixed_Sample_Locations (Object : Framebuffer; Value : Boolean);
function Default_Width (Object : Framebuffer) return Size;
function Default_Height (Object : Framebuffer) return Size;
function Default_Layers (Object : Framebuffer) return Size;
function Default_Samples (Object : Framebuffer) return Size;
function Default_Fixed_Sample_Locations (Object : Framebuffer) return Boolean;
function Max_Framebuffer_Width return Size
with Post => Max_Framebuffer_Width'Result >= 16_384;
function Max_Framebuffer_Height return Size
with Post => Max_Framebuffer_Height'Result >= 16_384;
function Max_Framebuffer_Layers return Size
with Post => Max_Framebuffer_Layers'Result >= 2_048;
function Max_Framebuffer_Samples return Size
with Post => Max_Framebuffer_Samples'Result >= 4;
procedure Blit (Read_Object, Draw_Object : Framebuffer;
Src_X0, Src_Y0, Src_X1, Src_Y1,
Dst_X0, Dst_Y0, Dst_X1, Dst_Y1 : Int;
Mask : Buffers.Buffer_Bits;
Filter : Textures.Magnifying_Function);
-- Copy a rectangle of pixels in Read_Object framebuffer to a region
-- in Draw_Object framebuffer
procedure Clear_Color_Buffer
(Object : Framebuffer;
Index : Buffers.Draw_Buffer_Index;
Format_Type : Pixels.Extensions.Format_Type;
Value : Colors.Color);
procedure Clear_Depth_Buffer (Object : Framebuffer; Value : Buffers.Depth);
procedure Clear_Stencil_Buffer (Object : Framebuffer; Value : Buffers.Stencil_Index);
procedure Clear_Depth_And_Stencil_Buffer (Object : Framebuffer;
Depth_Value : Buffers.Depth;
Stencil_Value : Buffers.Stencil_Index);
type Framebuffer_Target (<>) is tagged limited private;
procedure Bind (Target : Framebuffer_Target;
Object : Framebuffer'Class);
function Status
(Object : Framebuffer;
Target : Framebuffer_Target'Class) return Framebuffer_Status;
Read_Target : constant Framebuffer_Target;
Draw_Target : constant Framebuffer_Target;
function Default_Framebuffer return Framebuffer;
private
for Framebuffer_Status use (Undefined => 16#8219#,
Complete => 16#8CD5#,
Incomplete_Attachment => 16#8CD6#,
Incomplete_Missing_Attachment => 16#8CD7#,
Incomplete_Draw_Buffer => 16#8CDB#,
Incomplete_Read_Buffer => 16#8CDC#,
Unsupported => 16#8CDD#,
Incomplete_Multisample => 16#8D56#,
Incomplete_Layer_Targets => 16#8DA8#);
for Framebuffer_Status'Size use Low_Level.Enum'Size;
for Attachment_Point use (Depth_Stencil_Attachment => 16#821A#,
Color_Attachment_0 => 16#8CE0#,
Color_Attachment_1 => 16#8CE1#,
Color_Attachment_2 => 16#8CE2#,
Color_Attachment_3 => 16#8CE3#,
Color_Attachment_4 => 16#8CE4#,
Color_Attachment_5 => 16#8CE5#,
Color_Attachment_6 => 16#8CE6#,
Color_Attachment_7 => 16#8CE7#,
Color_Attachment_8 => 16#8CE8#,
Color_Attachment_9 => 16#8CE9#,
Color_Attachment_10 => 16#8CEA#,
Color_Attachment_11 => 16#8CEB#,
Color_Attachment_12 => 16#8CEC#,
Color_Attachment_13 => 16#8CED#,
Color_Attachment_14 => 16#8CEE#,
Color_Attachment_15 => 16#8CEF#,
Depth_Attachment => 16#8D00#,
Stencil_Attachment => 16#8D20#);
for Attachment_Point'Size use Low_Level.Enum'Size;
for Default_Attachment_Point use
(Front_Left => 16#0400#,
Front_Right => 16#0401#,
Back_Left => 16#0402#,
Back_Right => 16#0403#,
Depth => 16#1801#,
Stencil => 16#1802#);
for Default_Attachment_Point'Size use Low_Level.Enum'Size;
pragma Convention (C, Attachment_List);
pragma Convention (C, Default_Attachment_List);
type Framebuffer is new GL_Object with null record;
type Framebuffer_Target (Kind : Enums.Framebuffer_Kind) is
tagged limited null record;
Read_Target : constant Framebuffer_Target :=
Framebuffer_Target'(Kind => Enums.Read);
Draw_Target : constant Framebuffer_Target :=
Framebuffer_Target'(Kind => Enums.Draw);
end GL.Objects.Framebuffers;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2013 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Buffers;
with GL.Low_Level.Enums;
with GL.Objects.Textures;
with GL.Pixels.Extensions;
with GL.Types.Colors;
private with GL.Enums;
package GL.Objects.Framebuffers is
pragma Preelaborate;
use all type GL.Low_Level.Enums.Texture_Kind;
type Framebuffer_Status is (Undefined, Complete, Incomplete_Attachment,
Incomplete_Missing_Attachment,
Incomplete_Draw_Buffer, Incomplete_Read_Buffer,
Unsupported, Incomplete_Multisample,
Incomplete_Layer_Targets);
type Attachment_Point is (Depth_Stencil_Attachment,
Color_Attachment_0, Color_Attachment_1,
Color_Attachment_2, Color_Attachment_3,
Color_Attachment_4, Color_Attachment_5,
Color_Attachment_6, Color_Attachment_7,
Color_Attachment_8, Color_Attachment_9,
Color_Attachment_10, Color_Attachment_11,
Color_Attachment_12, Color_Attachment_13,
Color_Attachment_14, Color_Attachment_15,
Depth_Attachment, Stencil_Attachment);
type Default_Attachment_Point is
(Front_Left, Front_Right, Back_Left, Back_Right, Depth, Stencil);
type Attachment_List is array (Positive range <>) of Attachment_Point;
type Default_Attachment_List is array (Positive range <>) of Default_Attachment_Point;
function Valid_Attachment
(Attachment : Attachment_Point;
Texture : Textures.Texture) return Boolean
with Pre => not Texture.Compressed and Texture.Allocated;
type Framebuffer is new GL_Object with private;
overriding
procedure Initialize_Id (Object : in out Framebuffer);
overriding
procedure Delete_Id (Object : in out Framebuffer);
overriding
function Identifier (Object : Framebuffer) return Types.Debug.Identifier is
(Types.Debug.Framebuffer);
procedure Set_Draw_Buffer
(Object : Framebuffer;
Selector : Buffers.Color_Buffer_Selector)
with Pre => (if Object = Default_Framebuffer then
Selector in Buffers.Default_Color_Buffer_Selector | Buffers.None
else
Selector in Buffers.Explicit_Color_Buffer_Selector | Buffers.None);
procedure Set_Draw_Buffers
(Object : Framebuffer;
List : Buffers.Color_Buffer_List)
with Pre => (if Object = Default_Framebuffer then
(for all S of List =>
S in Buffers.Default_Color_Buffer_Selector | Buffers.None)
else
(for all S of List =>
S in Buffers.Explicit_Color_Buffer_Selector | Buffers.None));
procedure Set_Read_Buffer (Object : Framebuffer; Selector : Buffers.Color_Buffer_Selector)
with Pre => (if Object = Default_Framebuffer then
Selector in Buffers.Default_Color_Buffer_Selector | Buffers.None
else
Selector in Buffers.Explicit_Color_Buffer_Selector | Buffers.None);
procedure Attach_Texture
(Object : Framebuffer;
Attachment : Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level)
with Pre => Object /= Default_Framebuffer and
Valid_Attachment (Attachment, Texture) and
(if Texture.Kind in
Texture_2D_Multisample | Texture_2D_Multisample_Array
then Level = 0);
procedure Attach_Texture_Layer
(Object : Framebuffer;
Attachment : Attachment_Point;
Texture : Textures.Texture;
Level : Textures.Mipmap_Level;
Layer : Natural)
with Pre => Object /= Default_Framebuffer and
Valid_Attachment (Attachment, Texture) and
Texture.Layered;
procedure Detach (Object : Framebuffer; Attachment : Attachment_Point)
with Pre => Object /= Default_Framebuffer;
procedure Invalidate_Data
(Object : Framebuffer;
Attachments : Attachment_List)
with Pre => Object /= Default_Framebuffer;
procedure Invalidate_Sub_Data
(Object : Framebuffer;
Attachments : Attachment_List;
X, Y : Int;
Width, Height : Size)
with Pre => Object /= Default_Framebuffer;
procedure Invalidate_Data
(Object : Framebuffer;
Attachments : Default_Attachment_List)
with Pre => Object = Default_Framebuffer;
procedure Invalidate_Sub_Data
(Object : Framebuffer;
Attachments : Default_Attachment_List;
X, Y : Int;
Width, Height : Size)
with Pre => Object = Default_Framebuffer;
----------------------------------------------------------------------------
procedure Set_Default_Width (Object : Framebuffer; Value : Size)
with Pre => Object /= Default_Framebuffer;
procedure Set_Default_Height (Object : Framebuffer; Value : Size)
with Pre => Object /= Default_Framebuffer;
procedure Set_Default_Layers (Object : Framebuffer; Value : Size)
with Pre => Object /= Default_Framebuffer;
procedure Set_Default_Samples (Object : Framebuffer; Value : Size)
with Pre => Object /= Default_Framebuffer;
procedure Set_Default_Fixed_Sample_Locations (Object : Framebuffer; Value : Boolean)
with Pre => Object /= Default_Framebuffer;
function Default_Width (Object : Framebuffer) return Size
with Pre => Object /= Default_Framebuffer;
function Default_Height (Object : Framebuffer) return Size
with Pre => Object /= Default_Framebuffer;
function Default_Layers (Object : Framebuffer) return Size
with Pre => Object /= Default_Framebuffer;
function Default_Samples (Object : Framebuffer) return Size
with Pre => Object /= Default_Framebuffer;
function Default_Fixed_Sample_Locations (Object : Framebuffer) return Boolean
with Pre => Object /= Default_Framebuffer;
----------------------------------------------------------------------------
function Max_Framebuffer_Width return Size
with Post => Max_Framebuffer_Width'Result >= 16_384;
function Max_Framebuffer_Height return Size
with Post => Max_Framebuffer_Height'Result >= 16_384;
function Max_Framebuffer_Layers return Size
with Post => Max_Framebuffer_Layers'Result >= 2_048;
function Max_Framebuffer_Samples return Size
with Post => Max_Framebuffer_Samples'Result >= 4;
procedure Blit (Read_Object, Draw_Object : Framebuffer;
Src_X0, Src_Y0, Src_X1, Src_Y1,
Dst_X0, Dst_Y0, Dst_X1, Dst_Y1 : Int;
Mask : Buffers.Buffer_Bits;
Filter : Textures.Magnifying_Function);
-- Copy a rectangle of pixels in Read_Object framebuffer to a region
-- in Draw_Object framebuffer
procedure Clear_Color_Buffer
(Object : Framebuffer;
Index : Buffers.Draw_Buffer_Index;
Format_Type : Pixels.Extensions.Format_Type;
Value : Colors.Color);
procedure Clear_Depth_Buffer (Object : Framebuffer; Value : Buffers.Depth);
procedure Clear_Stencil_Buffer (Object : Framebuffer; Value : Buffers.Stencil_Index);
procedure Clear_Depth_And_Stencil_Buffer (Object : Framebuffer;
Depth_Value : Buffers.Depth;
Stencil_Value : Buffers.Stencil_Index);
type Framebuffer_Target (<>) is tagged limited private;
procedure Bind (Target : Framebuffer_Target;
Object : Framebuffer'Class);
function Status
(Object : Framebuffer;
Target : Framebuffer_Target'Class) return Framebuffer_Status;
Read_Target : constant Framebuffer_Target;
Draw_Target : constant Framebuffer_Target;
function Default_Framebuffer return Framebuffer;
private
for Framebuffer_Status use (Undefined => 16#8219#,
Complete => 16#8CD5#,
Incomplete_Attachment => 16#8CD6#,
Incomplete_Missing_Attachment => 16#8CD7#,
Incomplete_Draw_Buffer => 16#8CDB#,
Incomplete_Read_Buffer => 16#8CDC#,
Unsupported => 16#8CDD#,
Incomplete_Multisample => 16#8D56#,
Incomplete_Layer_Targets => 16#8DA8#);
for Framebuffer_Status'Size use Low_Level.Enum'Size;
for Attachment_Point use (Depth_Stencil_Attachment => 16#821A#,
Color_Attachment_0 => 16#8CE0#,
Color_Attachment_1 => 16#8CE1#,
Color_Attachment_2 => 16#8CE2#,
Color_Attachment_3 => 16#8CE3#,
Color_Attachment_4 => 16#8CE4#,
Color_Attachment_5 => 16#8CE5#,
Color_Attachment_6 => 16#8CE6#,
Color_Attachment_7 => 16#8CE7#,
Color_Attachment_8 => 16#8CE8#,
Color_Attachment_9 => 16#8CE9#,
Color_Attachment_10 => 16#8CEA#,
Color_Attachment_11 => 16#8CEB#,
Color_Attachment_12 => 16#8CEC#,
Color_Attachment_13 => 16#8CED#,
Color_Attachment_14 => 16#8CEE#,
Color_Attachment_15 => 16#8CEF#,
Depth_Attachment => 16#8D00#,
Stencil_Attachment => 16#8D20#);
for Attachment_Point'Size use Low_Level.Enum'Size;
for Default_Attachment_Point use
(Front_Left => 16#0400#,
Front_Right => 16#0401#,
Back_Left => 16#0402#,
Back_Right => 16#0403#,
Depth => 16#1801#,
Stencil => 16#1802#);
for Default_Attachment_Point'Size use Low_Level.Enum'Size;
pragma Convention (C, Attachment_List);
pragma Convention (C, Default_Attachment_List);
type Framebuffer is new GL_Object with null record;
type Framebuffer_Target (Kind : Enums.Framebuffer_Kind) is
tagged limited null record;
Read_Target : constant Framebuffer_Target :=
Framebuffer_Target'(Kind => Enums.Read);
Draw_Target : constant Framebuffer_Target :=
Framebuffer_Target'(Kind => Enums.Draw);
end GL.Objects.Framebuffers;
|
Add aspect Pre to setters/getters of default values of FBs
|
gl: Add aspect Pre to setters/getters of default values of FBs
Setting or getting certain default values of framebuffers is not allowed
for the default framebuffer.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
fc06966f8496e4b0cb8c411b70304f195321c0dd
|
awa/plugins/awa-images/regtests/awa-images-modules-tests.ads
|
awa/plugins/awa-images/regtests/awa-images-modules-tests.ads
|
-----------------------------------------------------------------------
-- awa-images-modules-tests -- Unit tests for image service
-- Copyright (C) 2012, 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with AWA.Tests;
with ADO;
package AWA.Images.Modules.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Id : ADO.Identifier;
Manager : AWA.Images.Modules.Image_Module_Access;
end record;
-- Test creation of a storage object
procedure Test_Create_Image (T : in out Test);
end AWA.Images.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-images-modules-tests -- Unit tests for image service
-- Copyright (C) 2012, 2013, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with AWA.Tests;
with ADO;
package AWA.Images.Modules.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Id : ADO.Identifier;
Manager : AWA.Images.Modules.Image_Module_Access;
end record;
-- Test creation of a storage object
procedure Test_Create_Image (T : in out Test);
-- Test the Get_Sizes operation.
procedure Test_Get_Sizes (T : in out TesT);
end AWA.Images.Modules.Tests;
|
Add Test_Get_Sizes procedure
|
Add Test_Get_Sizes procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e6612a617595331e885b2dd1eea2877e5c2c6648
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Blog);
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Status (Status);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Permissions.Services;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with ADO.Sessions;
with Ada.Calendar;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Workspace_Id : in ADO.Identifier;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Blog);
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Create_Date (Ada.Calendar.Clock);
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Status : in AWA.Blogs.Models.Post_Status_Type) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Save (DB);
Ctx.Commit;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
end AWA.Blogs.Modules;
|
Update the post URI to save it in DB
|
Update the post URI to save it in DB
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
aaf0c48593bb47fd8e53142a3691711a6b02e0ea
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Service : Modules.Question_Module_Access := null;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record
Service : Modules.Question_Module_Access := null;
Question : AWA.Questions.Models.Question_Ref;
end record;
type Answer_Bean_Access is access all Answer_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the answer.
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the answer bean instance.
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Question_Info_List_Bean bean instance.
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Question_Display_Bean is new Util.Beans.Basic.Bean with record
Service : Modules.Question_Module_Access := null;
Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean;
Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access;
Question : aliased AWA.Questions.Models.Question_Display_Info;
Question_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Display_Bean_Access is access all Question_Display_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the Question_Display_Bean bean instance.
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
with AWA.Tags.Beans;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Service : Modules.Question_Module_Access := null;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record
Service : Modules.Question_Module_Access := null;
Question : AWA.Questions.Models.Question_Ref;
end record;
type Answer_Bean_Access is access all Answer_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the answer.
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the answer bean instance.
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Question_Info_List_Bean bean instance.
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Question_Display_Bean is new Util.Beans.Basic.Bean with record
Service : Modules.Question_Module_Access := null;
-- List of answers associated with the question.
Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean;
Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access;
-- The question.
Question : aliased AWA.Questions.Models.Question_Display_Info;
Question_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- 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 Question_Display_Bean_Access is access all Question_Display_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the Question_Display_Bean bean instance.
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Questions.Beans;
|
Add the list of tags associated with the question
|
Add the list of tags associated with the question
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
06c37126eb6c3436d3578f3eca169063c1c94214
|
awa/plugins/awa-tags/src/awa-tags-components.ads
|
awa/plugins/awa-tags/src/awa-tags-components.ads
|
-----------------------------------------------------------------------
-- awa-tags-components -- Tags component
-- 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.Basic;
with Util.Beans.Objects;
with Util.Strings.Vectors;
with EL.Expressions;
with ASF.Components.Html.Forms;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer;
with ASF.Events.Faces;
with ASF.Factory;
package AWA.Tags.Components is
use ASF.Contexts.Writer;
-- Get the Tags component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
-- ------------------------------
-- Input component
-- ------------------------------
-- The AWA input component overrides the ASF input component to build a compact component
-- that displays a label, the input field and the associated error message if necessary.
--
-- The generated HTML looks like:
--
-- <ul class='taglist'>
-- <li><span>tag</span></li>
-- </ul>
--
-- or
--
-- <input type='text' name='' value='tag'/>
--
type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record
-- List of tags that have been added.
Added : Util.Strings.Vectors.Vector;
-- List of tags that have been removed.
Deleted : Util.Strings.Vectors.Vector;
-- True if the submitted values are correct.
Is_Valid : Boolean := False;
end record;
type Tag_UIInput_Access is access all Tag_UIInput'Class;
-- Returns True if the tag component must be rendered as readonly.
function Is_Readonly (UI : in Tag_UIInput;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean;
-- Get the tag after convertion with the optional converter.
function Get_Tag (UI : in Tag_UIInput;
Tag : in Util.Beans.Objects.Object;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String;
-- Render the tag as a readonly item.
procedure Render_Readonly_Tag (UI : in Tag_UIInput;
Tag : in Util.Beans.Objects.Object;
Class : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the tag as a link.
procedure Render_Link_Tag (UI : in Tag_UIInput;
Name : in String;
Tag : in Util.Beans.Objects.Object;
Link : in EL.Expressions.Expression;
Class : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the tag for an input form.
procedure Render_Form_Tag (UI : in Tag_UIInput;
Id : in String;
Tag : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>.
procedure Render_Readonly (UI : in Tag_UIInput;
List : in Util.Beans.Basic.List_Bean_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the list of tags for a form.
procedure Render_Form (UI : in Tag_UIInput;
List : in Util.Beans.Basic.List_Bean_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the javascript to enable the tag edition.
procedure Render_Script (UI : in Tag_UIInput;
Id : in String;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Get the action method expression to invoke if the command is pressed.
-- ------------------------------
function Get_Action_Expression (UI : in Tag_UIInput;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return EL.Expressions.Method_Expression;
-- Decode any new state of the specified component from the request contained
-- in the specified context and store that state on the component.
--
-- During decoding, events may be enqueued for later processing
-- (by event listeners that have registered an interest), by calling
-- the <b>Queue_Event</b> on the associated component.
overriding
procedure Process_Decodes (UI : in out Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Perform the component tree processing required by the <b>Update Model Values</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows.
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Updates/b> of all facets and children.
-- <ul>
overriding
procedure Process_Updates (UI : in out Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
overriding
procedure Broadcast (UI : in out Tag_UIInput;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end AWA.Tags.Components;
|
-----------------------------------------------------------------------
-- awa-tags-components -- Tags component
-- 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.Basic;
with Util.Beans.Objects;
with Util.Strings.Vectors;
with EL.Expressions;
with ASF.Components.Html.Forms;
with ASF.Contexts.Faces;
with ASF.Contexts.Writer;
with ASF.Events.Faces;
with ASF.Factory;
-- == Tags Component ==
--
-- === Displaying a list of tags ===
-- The <tt>awa:tagList</tt> component displays a list of tags. Each tag can be rendered as
-- a link if the <tt>tagLink</tt> attribute is defined. The list of tags is passed in the
-- <tt>value</tt> attribute. When rending that list, the <tt>var</tt> attribute is used to
-- setup a variable with the tag value. The <tt>tagLink</tt> attribute is then evaluated
-- against that variable and the result defines the link.
--
-- <awa:tagList value='#{questionList.tags}' id='qtags' styleClass="tagedit-list"
-- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}"
-- var="tagName"
-- tagClass="tagedit-listelement tagedit-listelement-old"/>
--
-- === Tag editing ===
-- The <tt>awa:tagList</tt> component allows to add or remove tags associated with a given
-- database entity. The tag management works with the jQuery plugin <b>Tagedit</b>. For this,
-- the page must include the <b>/js/jquery.tagedit.js</b> Javascript resource.
--
-- The tag edition is active only if the <tt>awa:tagList</tt> component is placed within an
-- <tt>h:form</tt> component. The <tt>value</tt> attribute defines the list of tags. This must
-- be a <tt>Tag_List_Bean</tt> object.
--
-- <awa:tagList value='#{question.tags}' id='qtags'
-- autoCompleteUrl='#{contextPath}/questions/lists/tag-search.html'/>
--
-- When the form is submitted and validated, the procedure <tt>Set_Added</tt> and
-- <tt>Set_Deleted</tt> are called on the value bean with the list of tags that were
-- added and removed. These operations are called in the <tt>UPDATE_MODEL_VALUES</tt>
-- phase (ie, before calling the action's bean operation).
--
package AWA.Tags.Components is
use ASF.Contexts.Writer;
-- Get the Tags component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
-- ------------------------------
-- Input component
-- ------------------------------
-- The AWA input component overrides the ASF input component to build a compact component
-- that displays a label, the input field and the associated error message if necessary.
--
-- The generated HTML looks like:
--
-- <ul class='taglist'>
-- <li><span>tag</span></li>
-- </ul>
--
-- or
--
-- <input type='text' name='' value='tag'/>
--
type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record
-- List of tags that have been added.
Added : Util.Strings.Vectors.Vector;
-- List of tags that have been removed.
Deleted : Util.Strings.Vectors.Vector;
-- True if the submitted values are correct.
Is_Valid : Boolean := False;
end record;
type Tag_UIInput_Access is access all Tag_UIInput'Class;
-- Returns True if the tag component must be rendered as readonly.
function Is_Readonly (UI : in Tag_UIInput;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean;
-- Get the tag after convertion with the optional converter.
function Get_Tag (UI : in Tag_UIInput;
Tag : in Util.Beans.Objects.Object;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String;
-- Render the tag as a readonly item.
procedure Render_Readonly_Tag (UI : in Tag_UIInput;
Tag : in Util.Beans.Objects.Object;
Class : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the tag as a link.
procedure Render_Link_Tag (UI : in Tag_UIInput;
Name : in String;
Tag : in Util.Beans.Objects.Object;
Link : in EL.Expressions.Expression;
Class : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the tag for an input form.
procedure Render_Form_Tag (UI : in Tag_UIInput;
Id : in String;
Tag : in Util.Beans.Objects.Object;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>.
procedure Render_Readonly (UI : in Tag_UIInput;
List : in Util.Beans.Basic.List_Bean_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the list of tags for a form.
procedure Render_Form (UI : in Tag_UIInput;
List : in Util.Beans.Basic.List_Bean_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the javascript to enable the tag edition.
procedure Render_Script (UI : in Tag_UIInput;
Id : in String;
Writer : in Response_Writer_Access;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
overriding
procedure Encode_Begin (UI : in Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Render the end of the input component. Closes the DL/DD list.
overriding
procedure Encode_End (UI : in Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Get the action method expression to invoke if the command is pressed.
function Get_Action_Expression (UI : in Tag_UIInput;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return EL.Expressions.Method_Expression;
-- Decode any new state of the specified component from the request contained
-- in the specified context and store that state on the component.
--
-- During decoding, events may be enqueued for later processing
-- (by event listeners that have registered an interest), by calling
-- the <b>Queue_Event</b> on the associated component.
overriding
procedure Process_Decodes (UI : in out Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Perform the component tree processing required by the <b>Update Model Values</b>
-- phase of the request processing lifecycle for all facets of this component,
-- all children of this component, and this component itself, as follows.
-- <ul>
-- <li>If this component <b>rendered</b> property is false, skip further processing.
-- <li>Call the <b>Process_Updates/b> of all facets and children.
-- <ul>
overriding
procedure Process_Updates (UI : in out Tag_UIInput;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
overriding
procedure Broadcast (UI : in out Tag_UIInput;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
end AWA.Tags.Components;
|
Document how to use the <awa:tagList> component
|
Document how to use the <awa:tagList> component
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
116f48b8479a0c2e82bca584e88a9391f1604dfa
|
awa/plugins/awa-comments/src/awa-comments.ads
|
awa/plugins/awa-comments/src/awa-comments.ads
|
-----------------------------------------------------------------------
-- awa-comments -- Comments module
-- Copyright (C) 2009, 2010, 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Comments</b> module is a general purpose module that allows to associate user comments
-- to any database entity. The module defines several bean types that allow to display a list
-- of comments or edit and publish a new comment.
--
-- == Model ==
-- The database model is generic and it uses the <tt>Entity_Type</tt> provided by
-- [https://github.com/stcarrez/ada-ado ADO] to associate a comment to entities stored in different
-- tables. The <tt>Entity_Type</tt> identifies the database table and the stored identifier
-- in <tt>for_entity_id</tt> defines the entity in that table.
--
-- [images/awa_comments_model.png]
--
-- @include awa-comments-modules.ads
-- @include awa-comments-beans.ads
-- @include comment-queries.xml
--
package AWA.Comments is
end AWA.Comments;
|
-----------------------------------------------------------------------
-- awa-comments -- Comments module
-- Copyright (C) 2009, 2010, 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Comments</b> module is a general purpose module that allows to associate user comments
-- to any database entity. The module defines several bean types that allow to display a list
-- of comments or edit and publish a new comment.
--
-- == Model ==
-- The database model is generic and it uses the <tt>Entity_Type</tt> provided by
-- [https://github.com/stcarrez/ada-ado ADO] to associate a comment to entities stored in
-- different tables. The <tt>Entity_Type</tt> identifies the database table and the stored
-- identifier in <tt>for_entity_id</tt> defines the entity in that table.
--
-- [images/awa_comments_model.png]
--
-- @include awa-comments-modules.ads
-- @include awa-comments-beans.ads
-- @include comment-queries.xml
--
package AWA.Comments is
end AWA.Comments;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
bac74dca5916031378aab99eae6784114b6bfd75
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a section header in the document.
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Html_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams.Html;
with Wiki.Strings;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a section header in the document.
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
end Wiki.Render.Html;
|
Remove Add_Line_Break procedure
|
Remove Add_Line_Break procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.