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
|
---|---|---|---|---|---|---|---|---|---|
d69497f7f51111d4bdffcfab0e6a0daeaa6c709e
|
src/wiki-writers.adb
|
src/wiki-writers.adb
|
-----------------------------------------------------------------------
-- wiki-writers -- Wiki writers
-- 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.Strings.Unbounded;
with Wiki.Writers.Builders;
package body Wiki.Writers is
procedure foo is
begin
null;
end foo;
end Wiki.Writers;
|
-----------------------------------------------------------------------
-- wiki-writers -- Wiki writers
-- 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 Wiki.Writers is
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Attribute (Writer : in out Html_writer_Type'Class;
Name : in String;
Content : in String) is
S : constant Wide_Wide_String := Ada.Characters.Conversions.To_Wide_Wide_String (Content);
begin
Writer.Write_Wide_Attribute (Name, To_Unbounded_Wide_Wide_String (S));
end Write_Attribute;
end Wiki.Writers;
|
Implement the Write_Attribute procedure
|
Implement the Write_Attribute procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
0409b95e72ab8cc532da838919ec4066a497035d
|
tools/druss-commands-bboxes.adb
|
tools/druss-commands-bboxes.adb
|
-----------------------------------------------------------------------
-- druss-commands-bboxes -- Commands to manage the bboxes
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Properties;
with Util.Strings;
with Util.Strings.Sets;
with Bbox.API;
with Druss.Gateways;
with Druss.Config;
with UPnP.SSDP;
package body Druss.Commands.Bboxes is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
use type Ada.Streams.Stream_Element;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes");
-- ------------------------------
-- Add the bbox with the given IP address.
-- ------------------------------
procedure Add_Bbox (Command : in Command_Type;
IP : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Box : Bbox.API.Client_Type;
Info : Util.Properties.Manager;
Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP);
begin
if not Gw.Is_Null then
Log.Debug ("Bbox {0} is already registered", IP);
return;
end if;
Box.Set_Server (IP);
Box.Get ("device", Info);
if Info.Get ("device.modelname", "") /= "" then
Context.Console.Notice (N_INFO, "Found a new bbox at " & IP);
Gw := Druss.Gateways.Gateway_Refs.Create;
Gw.Value.Ip := Ada.Strings.Unbounded.To_Unbounded_String (IP);
Context.Gateways.Append (Gw);
end if;
exception
when others =>
Log.Debug ("Ignoring IP {0} because some exception happened", IP);
end Add_Bbox;
procedure Discover (Command : in Command_Type;
Context : in out Context_Type) is
procedure Process (URI : in String);
Retry : Natural := 0;
Scanner : UPnP.SSDP.Scanner_Type;
Itf_IPs : Util.Strings.Sets.Set;
procedure Process (URI : in String) is
Pos : Natural;
begin
if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then
return;
end if;
Pos := Util.Strings.Index (URI, ':', 6);
if Pos > 0 then
Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context);
end if;
end Process;
begin
Log.Info ("Discovering gateways on the network");
Scanner.Initialize;
Scanner.Find_IPv4_Addresses (Itf_IPs);
while Retry < 5 loop
Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs);
Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1",
Process'Access, 1.0);
Retry := Retry + 1;
end loop;
Druss.Config.Save_Gateways (Context.Gateways);
end Discover;
-- ------------------------------
-- Set the password to be used by the Bbox API to connect to the box.
-- ------------------------------
procedure Do_Password (Command : in Command_Type;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type) is
procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type;
Passwd : in String);
procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type;
Passwd : in String) is
begin
Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd);
end Change_Password;
begin
Druss.Commands.Gateway_Command (Command, Args, 2, Change_Password'Access, Context);
Druss.Config.Save_Gateways (Context.Gateways);
end Do_Password;
-- ------------------------------
-- Enable or disable the bbox management by Druss.
-- ------------------------------
procedure Do_Enable (Command : in Command_Type;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type) is
procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type;
Command : in String);
procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type;
Command : in String) is
begin
Gateway.Enable := Command = "enable";
end Change_Enable;
begin
Druss.Commands.Gateway_Command (Command, Args, 1, Change_Enable'Access, Context);
Druss.Config.Save_Gateways (Context.Gateways);
end Do_Enable;
-- ------------------------------
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
if Args.Get_Count = 0 then
Druss.Commands.Driver.Usage (Args);
elsif Args.Get_Argument (1) = "discover" then
Command.Discover (Context);
elsif Args.Get_Argument (1) = "password" then
Command.Do_Password (Args, Context);
elsif Args.Get_Argument (1) in "enable" | "disable" then
Command.Do_Enable (Args, Context);
else
Context.Console.Notice (N_USAGE, "Invalid sub-command: " & Args.Get_Argument (1));
Druss.Commands.Driver.Usage (Args);
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP,
"bbox: Manage and define the configuration to connect to the Bbox");
Console.Notice (N_HELP,
"Usage: bbox <operation>...");
Console.Notice (N_HELP,
"");
Console.Notice (N_HELP,
" Druss needs to know the list of Bboxes which are available"
& " on the network.");
Console.Notice (N_HELP,
" It also need some credentials to connect to the Bbox using"
& " the Bbox API.");
Console.Notice (N_HELP,
" The 'bbox' command allows to manage that list and configuration.");
Console.Notice (N_HELP,
" Examples:");
Console.Notice (N_HELP,
" bbox discover Discover the bbox(es) connected to the LAN");
Console.Notice (N_HELP,
" bbox add IP Add a bbox knowing its IP address");
Console.Notice (N_HELP,
" bbox del IP Delete a bbox from the list");
Console.Notice (N_HELP,
" bbox enable IP Enable the bbox (it will be used by Druss)");
Console.Notice (N_HELP,
" bbox disable IP Disable the bbox (it will not be managed)");
Console.Notice (N_HELP,
" bbox password <pass> [IP] Set the bbox API connection password");
end Help;
end Druss.Commands.Bboxes;
|
-----------------------------------------------------------------------
-- druss-commands-bboxes -- Commands to manage the bboxes
-- Copyright (C) 2017, 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.Streams;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Properties;
with Util.Strings;
with Util.Strings.Sets;
with Bbox.API;
with Druss.Gateways;
with Druss.Config;
with UPnP.SSDP;
package body Druss.Commands.Bboxes is
use Ada.Strings.Unbounded;
use type Ada.Streams.Stream_Element_Offset;
use type Ada.Streams.Stream_Element;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes");
-- ------------------------------
-- Add the bbox with the given IP address.
-- ------------------------------
procedure Add_Bbox (Command : in Command_Type;
IP : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Box : Bbox.API.Client_Type;
Info : Util.Properties.Manager;
Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP);
begin
if not Gw.Is_Null then
Log.Debug ("Bbox {0} is already registered", IP);
return;
end if;
Box.Set_Server (IP);
Box.Get ("device", Info);
if Info.Get ("device.modelname", "") /= "" then
Context.Console.Notice (N_INFO, "Found a new bbox at " & IP);
Gw := Druss.Gateways.Gateway_Refs.Create;
Gw.Value.Ip := Ada.Strings.Unbounded.To_Unbounded_String (IP);
Context.Gateways.Append (Gw);
end if;
exception
when others =>
Log.Debug ("Ignoring IP {0} because some exception happened", IP);
end Add_Bbox;
procedure Discover (Command : in Command_Type;
Context : in out Context_Type) is
procedure Process (URI : in String);
Retry : Natural := 0;
Scanner : UPnP.SSDP.Scanner_Type;
Itf_IPs : Util.Strings.Sets.Set;
procedure Process (URI : in String) is
Pos : Natural;
begin
if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then
return;
end if;
Pos := Util.Strings.Index (URI, ':', 6);
if Pos > 0 then
Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context);
end if;
end Process;
begin
Log.Info ("Discovering gateways on the network");
Scanner.Initialize;
Scanner.Find_IPv4_Addresses (Itf_IPs);
while Retry < 5 loop
Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs);
Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1",
Process'Access, 1.0);
Retry := Retry + 1;
end loop;
Druss.Config.Save_Gateways (Context.Gateways);
end Discover;
-- ------------------------------
-- Set the password to be used by the Bbox API to connect to the box.
-- ------------------------------
procedure Do_Password (Command : in Command_Type;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type) is
procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type;
Passwd : in String);
procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type;
Passwd : in String) is
begin
Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd);
end Change_Password;
begin
Druss.Commands.Gateway_Command (Command, Args, 2, Change_Password'Access, Context);
Druss.Config.Save_Gateways (Context.Gateways);
end Do_Password;
-- ------------------------------
-- Enable or disable the bbox management by Druss.
-- ------------------------------
procedure Do_Enable (Command : in Command_Type;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type) is
procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type;
Command : in String);
procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type;
Command : in String) is
begin
Gateway.Enable := Command = "enable";
end Change_Enable;
begin
Druss.Commands.Gateway_Command (Command, Args, 1, Change_Enable'Access, Context);
Druss.Config.Save_Gateways (Context.Gateways);
end Do_Enable;
-- ------------------------------
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
if Args.Get_Count = 0 then
Druss.Commands.Driver.Usage (Args, Context);
elsif Args.Get_Argument (1) = "discover" then
Command.Discover (Context);
elsif Args.Get_Argument (1) = "password" then
Command.Do_Password (Args, Context);
elsif Args.Get_Argument (1) in "enable" | "disable" then
Command.Do_Enable (Args, Context);
else
Context.Console.Notice (N_USAGE, "Invalid sub-command: " & Args.Get_Argument (1));
Druss.Commands.Driver.Usage (Args, Context);
end if;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP,
"bbox: Manage and define the configuration to connect to the Bbox");
Console.Notice (N_HELP,
"Usage: bbox <operation>...");
Console.Notice (N_HELP,
"");
Console.Notice (N_HELP,
" Druss needs to know the list of Bboxes which are available"
& " on the network.");
Console.Notice (N_HELP,
" It also need some credentials to connect to the Bbox using"
& " the Bbox API.");
Console.Notice (N_HELP,
" The 'bbox' command allows to manage that list and configuration.");
Console.Notice (N_HELP,
" Examples:");
Console.Notice (N_HELP,
" bbox discover Discover the bbox(es) connected to the LAN");
Console.Notice (N_HELP,
" bbox add IP Add a bbox knowing its IP address");
Console.Notice (N_HELP,
" bbox del IP Delete a bbox from the list");
Console.Notice (N_HELP,
" bbox enable IP Enable the bbox (it will be used by Druss)");
Console.Notice (N_HELP,
" bbox disable IP Disable the bbox (it will not be managed)");
Console.Notice (N_HELP,
" bbox password <pass> [IP] Set the bbox API connection password");
end Help;
end Druss.Commands.Bboxes;
|
Change Help command to accept in out command
|
Change Help command to accept in out command
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
5483ced878ee0db649ccc1f072a9fb32f342bd15
|
regtests/wiki-parsers-tests.adb
|
regtests/wiki-parsers-tests.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-tests -- Unit tests for wiki parsing
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Wiki.Utils;
with Wiki.Helpers;
package body Wiki.Parsers.Tests is
use Wiki.Helpers;
package Caller is new Util.Test_Caller (Test, "Wikis.Parsers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)",
Test_Wiki_Bold'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)",
Test_Wiki_Italic'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)",
Test_Wiki_Formats'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)",
Test_Wiki_Section'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)",
Test_Wiki_List'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)",
Test_Wiki_Link'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)",
Test_Wiki_Quote'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)",
Test_Wiki_Line_Break'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)",
Test_Wiki_Image'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)",
Test_Wiki_Preformatted'Access);
Caller.Add_Test (Suite, "Test Wiki.Text.Renderer",
Test_Wiki_Text_Renderer'Access);
end Add_Tests;
-- ------------------------------
-- Test bold rendering.
-- ------------------------------
procedure Test_Wiki_Bold (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>",
Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>",
Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX),
"Bold rendering invalid (MIX)");
Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>",
Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>",
Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR),
"No bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB),
"Bold rendering invalid (PHPBB)");
end Test_Wiki_Bold;
-- ------------------------------
-- Test italic rendering.
-- ------------------------------
procedure Test_Wiki_Italic (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>item</i></p>",
Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>",
Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
end Test_Wiki_Italic;
-- ------------------------------
-- Test various format rendering.
-- ------------------------------
procedure Test_Wiki_Formats (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>",
Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE),
"Italic+Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE),
"Italic rendering invalid");
end Test_Wiki_Formats;
-- ------------------------------
-- Test heading rendering.
-- ------------------------------
procedure Test_Wiki_Section (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<h1>item</h1>",
Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h2>item</h2>",
Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE),
"H2 rendering invalid");
Util.Tests.Assert_Equals (T, "<h3>item</h3>",
Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE),
"H3 rendering invalid");
Util.Tests.Assert_Equals (T, "<h4>item</h4>",
Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE),
"H4 rendering invalid");
Util.Tests.Assert_Equals (T, "<h5>item</h5>",
Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE),
"H5 rendering invalid");
Util.Tests.Assert_Equals (T, "<h6>item</h6>",
Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE),
"H6 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>",
Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==",
SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>",
Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =",
SYNTAX_GOOGLE),
"H1 rendering invalid");
end Test_Wiki_Section;
-- ------------------------------
-- Test list rendering.
-- ------------------------------
procedure Test_Wiki_List (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>",
Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE),
"Ordered list rendering invalid");
Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF &
"</li><li>item2 item2" & ASCII.LF &
"</li><li><ol>item3</li></ol></ol>",
Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3",
SYNTAX_GOOGLE),
"Ordered rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE),
"Bullet list rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR),
"Bullet list rendering invalid");
end Test_Wiki_List;
-- ------------------------------
-- Test link rendering.
-- ------------------------------
procedure Test_Wiki_Link (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""http://www.joe.com/item"" lang=""en"" title=""some""" &
">name </a></p>",
Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]",
SYNTAX_DOTCLEAR),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p>[d</p>",
Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE),
"No link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a " &
"href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>",
Wiki.Utils.To_Html ("[http://www.joe.com/item]",
SYNTAX_DOTCLEAR),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[[name]]", SYNTAX_MEDIA_WIKI),
"Link rendering invalid");
end Test_Wiki_Link;
-- ------------------------------
-- Test quote rendering.
-- ------------------------------
procedure Test_Wiki_Quote (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>",
Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>",
Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q cite=""http://www.sun.com"" lang=""en"">quote</q></p>",
Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}",
SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p>{quote}}</p>",
Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR),
"No quote rendering invalid");
end Test_Wiki_Quote;
-- ------------------------------
-- Test line break rendering.
-- ------------------------------
procedure Test_Wiki_Line_Break (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p>a<br />b</p>",
Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a<br />b</p>",
Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%%b</p>",
Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%b</p>",
Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
end Test_Wiki_Line_Break;
-- ------------------------------
-- Test image rendering.
-- ------------------------------
procedure Test_Wiki_Image (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img alt=""title"" " &
"src=""/image/t.png"" longdesc=""describe"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png|title|D|describe))",
SYNTAX_DOTCLEAR),
"Image rendering invalid");
end Test_Wiki_Image;
-- ------------------------------
-- Test preformatted rendering.
-- ------------------------------
procedure Test_Wiki_Preformatted (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>",
Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>",
Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x"
& ASCII.LF & "</pre>",
Wiki.Utils.To_Html (" item1 x" & LF & " item2 x" & LF & " item3 x",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x"
& ASCII.LF & "item3 x"
& ASCII.LF & "</pre>",
Wiki.Utils.To_Html (" item1 x" & CR & LF & " item2 x"
& CR & LF & " item3 x",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
end Test_Wiki_Preformatted;
-- ------------------------------
-- Test the text renderer.
-- ------------------------------
procedure Test_Wiki_Text_Renderer (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, ASCII.LF & "code",
Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF,
Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE),
"Preformat rendering invalid");
end Test_Wiki_Text_Renderer;
end Wiki.Parsers.Tests;
|
-----------------------------------------------------------------------
-- wiki-parsers-tests -- Unit tests for wiki parsing
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Wiki.Utils;
with Wiki.Helpers;
package body Wiki.Parsers.Tests is
use Wiki.Helpers;
package Caller is new Util.Test_Caller (Test, "Wikis.Parsers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)",
Test_Wiki_Bold'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)",
Test_Wiki_Italic'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)",
Test_Wiki_Formats'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)",
Test_Wiki_Section'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)",
Test_Wiki_List'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)",
Test_Wiki_Link'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)",
Test_Wiki_Quote'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)",
Test_Wiki_Line_Break'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)",
Test_Wiki_Image'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)",
Test_Wiki_Preformatted'Access);
Caller.Add_Test (Suite, "Test Wiki.Text.Renderer",
Test_Wiki_Text_Renderer'Access);
end Add_Tests;
-- ------------------------------
-- Test bold rendering.
-- ------------------------------
procedure Test_Wiki_Bold (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>",
Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>",
Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX),
"Bold rendering invalid (MIX)");
Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>",
Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>",
Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR),
"No bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB),
"Bold rendering invalid (PHPBB)");
end Test_Wiki_Bold;
-- ------------------------------
-- Test italic rendering.
-- ------------------------------
procedure Test_Wiki_Italic (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>item</i></p>",
Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>",
Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
end Test_Wiki_Italic;
-- ------------------------------
-- Test various format rendering.
-- ------------------------------
procedure Test_Wiki_Formats (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>",
Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE),
"Italic+Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE),
"Italic rendering invalid");
end Test_Wiki_Formats;
-- ------------------------------
-- Test heading rendering.
-- ------------------------------
procedure Test_Wiki_Section (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<h1>item</h1>",
Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h2>item</h2>",
Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE),
"H2 rendering invalid");
Util.Tests.Assert_Equals (T, "<h3>item</h3>",
Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE),
"H3 rendering invalid");
Util.Tests.Assert_Equals (T, "<h4>item</h4>",
Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE),
"H4 rendering invalid");
Util.Tests.Assert_Equals (T, "<h5>item</h5>",
Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE),
"H5 rendering invalid");
Util.Tests.Assert_Equals (T, "<h6>item</h6>",
Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE),
"H6 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>",
Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==",
SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>",
Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==",
SYNTAX_GOOGLE),
"H1 rendering invalid");
end Test_Wiki_Section;
-- ------------------------------
-- Test list rendering.
-- ------------------------------
procedure Test_Wiki_List (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>",
Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE),
"Ordered list rendering invalid");
Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF &
"</li><li>item2 item2" & ASCII.LF &
"</li><li><ol>item3</li></ol></ol>",
Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3",
SYNTAX_GOOGLE),
"Ordered rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE),
"Bullet list rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR),
"Bullet list rendering invalid");
end Test_Wiki_List;
-- ------------------------------
-- Test link rendering.
-- ------------------------------
procedure Test_Wiki_Link (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""http://www.joe.com/item"" lang=""en"" title=""some""" &
">name </a></p>",
Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]",
SYNTAX_DOTCLEAR),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p>[d</p>",
Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE),
"No link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a " &
"href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>",
Wiki.Utils.To_Html ("[http://www.joe.com/item]",
SYNTAX_DOTCLEAR),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[[name]]", SYNTAX_MEDIA_WIKI),
"Link rendering invalid");
end Test_Wiki_Link;
-- ------------------------------
-- Test quote rendering.
-- ------------------------------
procedure Test_Wiki_Quote (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>",
Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>",
Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q cite=""http://www.sun.com"" lang=""en"">quote</q></p>",
Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}",
SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p>{quote}}</p>",
Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR),
"No quote rendering invalid");
end Test_Wiki_Quote;
-- ------------------------------
-- Test line break rendering.
-- ------------------------------
procedure Test_Wiki_Line_Break (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p>a<br />b</p>",
Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a<br />b</p>",
Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%%b</p>",
Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%b</p>",
Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
end Test_Wiki_Line_Break;
-- ------------------------------
-- Test image rendering.
-- ------------------------------
procedure Test_Wiki_Image (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img alt=""title"" " &
"src=""/image/t.png"" longdesc=""describe"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png|title|D|describe))",
SYNTAX_DOTCLEAR),
"Image rendering invalid");
end Test_Wiki_Image;
-- ------------------------------
-- Test preformatted rendering.
-- ------------------------------
procedure Test_Wiki_Preformatted (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>",
Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>",
Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x"
& ASCII.LF & "</pre>",
Wiki.Utils.To_Html (" item1 x" & LF & " item2 x" & LF & " item3 x",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x"
& ASCII.LF & "item3 x"
& ASCII.LF & "</pre>",
Wiki.Utils.To_Html (" item1 x" & CR & LF & " item2 x"
& CR & LF & " item3 x",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
end Test_Wiki_Preformatted;
-- ------------------------------
-- Test the text renderer.
-- ------------------------------
procedure Test_Wiki_Text_Renderer (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, ASCII.LF & "code",
Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF,
Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE),
"Preformat rendering invalid");
end Test_Wiki_Text_Renderer;
end Wiki.Parsers.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
2b544bd0de434fe23518d112113e2aa59ed4da92
|
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
|
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-tags-modules-tests -- Unit tests for tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Votes.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Tags.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Votes.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag",
Test_Add_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag",
Test_Remove_Tag'Access);
end Add_Tests;
-- ------------------------------
-- Test tag creation.
-- ------------------------------
procedure Test_Add_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
end;
end Test_Add_Tag;
-- ------------------------------
-- Test tag removal.
-- ------------------------------
procedure Test_Remove_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
end;
end Test_Remove_Tag;
end AWA.Tags.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-tags-modules-tests -- Unit tests for tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Tags.Beans;
package body AWA.Tags.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Tags.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag",
Test_Add_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag",
Test_Remove_Tag'Access);
end Add_Tests;
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access is
Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module);
begin
return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Test tag creation.
-- ------------------------------
procedure Test_Add_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
-- Create a tag.
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
-- Load the list.
List.Load_Tags (User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
end;
end Test_Add_Tag;
-- ------------------------------
-- Test tag removal.
-- ------------------------------
procedure Test_Remove_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
-- Load the list.
List.Load_Tags (User.Get_Id);
Util.Tests.Assert_Equals (T, 2, Integer (List.Get_Count), "Invalid number of tags");
end;
end Test_Remove_Tag;
end AWA.Tags.Modules.Tests;
|
Use the Tag_List_Bean to check that the tags are created/removed
|
Use the Tag_List_Bean to check that the tags are created/removed
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a418e90327083371fb35b371f1deee4c9f6709db
|
mat/src/events/mat-events-targets.ads
|
mat/src/events/mat-events-targets.ads
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
type Event_Type is mod 16;
type Probe_Index_Type is mod 16;
type Probe_Event_Type is record
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
private
EVENT_BLOCK_SIZE : constant Positive := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Natural := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
private
Current : Event_Block_Access := null;
Events : Event_Map;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
type Event_Type is mod 16;
type Probe_Index_Type is mod 16;
type Probe_Event_Type is record
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Time;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
private
EVENT_BLOCK_SIZE : constant Positive := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Natural := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
private
Current : Event_Block_Access := null;
Events : Event_Map;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
Declare the Get_Time_Range protected procedure
|
Declare the Get_Time_Range protected procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
09deaabd2bc22026fac3f37abfe617b8408736d8
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map) is
begin
Memory.Memory.Thread_Information (Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
Memory.Memory.Frame_Information (Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Filter, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation);
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
pragma Unreferenced (Key);
begin
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
Pos : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end if;
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Threads : in out Memory_Info_Map) is
begin
MAT.Memory.Tools.Thread_Information (Used_Slots, Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into);
end Find;
end Memory_Allocator;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map) is
begin
Memory.Memory.Thread_Information (Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
Memory.Memory.Frame_Information (Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Filter, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation);
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
pragma Unreferenced (Key);
begin
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
Pos : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end if;
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Threads : in out Memory_Info_Map) is
begin
MAT.Memory.Tools.Thread_Information (Used_Slots, Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into);
end Find;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Implement the Stat_Information protected operation
|
Implement the Stat_Information protected operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
cd5edb5846e210778d6f071ba3e80ff6d2dce6b0
|
src/util-encoders.ads
|
src/util-encoders.ads
|
-----------------------------------------------------------------------
-- util-encoders -- Encode/Decode streams and strings from one format to another
-- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Interfaces;
-- === Encoder and Decoders ===
-- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects
-- which provide a mechanism to transform a stream from one format into
-- another format.
--
-- ==== Simple encoding and decoding ====
--
package Util.Encoders is
pragma Preelaborate;
Not_Supported : exception;
Encoding_Error : exception;
-- Encoder/decoder for Base64 (RFC 4648)
BASE_64 : constant String := "base64";
-- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet
-- (+ and / are replaced by - and _)
BASE_64_URL : constant String := "base64url";
-- Encoder/decoder for Base16 (RFC 4648)
BASE_16 : constant String := "base16";
HEX : constant String := "hex";
-- Encoder for SHA1 (RFC 3174)
HASH_SHA1 : constant String := "sha1";
-- ------------------------------
-- Encoder context object
-- ------------------------------
-- The <b>Encoder</b> provides operations to encode and decode
-- strings or stream of data from one format to another.
-- The <b>Encoded</b> contains two <b>Transformer</b>
-- which either <i>encodes</i> or <i>decodes</i> the stream.
type Encoder is tagged limited private;
-- Encodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be encoded.
-- Raises the <b>Not_Supported</b> exception if the encoding is not
-- supported.
function Encode (E : in Encoder;
Data : in String) return String;
-- Create the encoder object for the specified encoding format.
function Create (Name : in String) return Encoder;
type Decoder is tagged limited private;
-- Decodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be decoded.
-- Raises the <b>Not_Supported</b> exception if the decoding is not
-- supported.
function Decode (E : in Decoder;
Data : in String) return String;
-- Create the decoder object for the specified encoding format.
function Create (Name : in String) return Decoder;
-- ------------------------------
-- Stream Transformation interface
-- ------------------------------
-- The <b>Transformer</b> interface defines the operation to transform
-- a stream from one data format to another.
type Transformer is limited interface;
type Transformer_Access is access all Transformer'Class;
-- Transform the input array represented by <b>Data</b> into
-- the output array <b>Into</b>. The transformation made by
-- the object can be of any nature (Hex encoding, Base64 encoding,
-- Hex decoding, Base64 decoding, encryption, compression, ...).
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> array.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output array <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- array cannot be transformed.
procedure Transform (E : in out Transformer;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Finish encoding the input array.
procedure Finish (E : in out Transformer;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset) is null;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in String) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer and return the data in
-- the <b>Into</b> array, setting <b>Last</b> to the last index.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
procedure Transform (E : in out Transformer'Class;
Data : in String;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting
-- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits
-- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated
-- to indicate the position of the last valid byte written in <tt>Into</tt>.
procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : in Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
-- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting
-- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated
-- to indicate the last position in the byte array.
procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : out Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
private
type Encoder is new Ada.Finalization.Limited_Controlled with record
Encode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Encoder);
type Decoder is new Ada.Finalization.Limited_Controlled with record
Decode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Decoder);
end Util.Encoders;
|
-----------------------------------------------------------------------
-- util-encoders -- Encode/Decode streams and strings from one format to another
-- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Interfaces;
-- === Encoder and Decoders ===
-- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects
-- which provide a mechanism to transform a stream from one format into
-- another format.
--
-- ==== Simple encoding and decoding ====
--
package Util.Encoders is
pragma Preelaborate;
Not_Supported : exception;
Encoding_Error : exception;
-- Encoder/decoder for Base64 (RFC 4648)
BASE_64 : constant String := "base64";
-- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet
-- (+ and / are replaced by - and _)
BASE_64_URL : constant String := "base64url";
-- Encoder/decoder for Base16 (RFC 4648)
BASE_16 : constant String := "base16";
HEX : constant String := "hex";
-- Encoder for SHA1 (RFC 3174)
HASH_SHA1 : constant String := "sha1";
-- ------------------------------
-- Encoder context object
-- ------------------------------
-- The <b>Encoder</b> provides operations to encode and decode
-- strings or stream of data from one format to another.
-- The <b>Encoded</b> contains two <b>Transformer</b>
-- which either <i>encodes</i> or <i>decodes</i> the stream.
type Encoder is tagged limited private;
-- Encodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be encoded.
-- Raises the <b>Not_Supported</b> exception if the encoding is not
-- supported.
function Encode (E : in Encoder;
Data : in String) return String;
function Encode (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array) return String;
-- Create the encoder object for the specified encoding format.
function Create (Name : in String) return Encoder;
type Decoder is tagged limited private;
-- Decodes the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> encoder.
--
-- Returns the encoded string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be decoded.
-- Raises the <b>Not_Supported</b> exception if the decoding is not
-- supported.
function Decode (E : in Decoder;
Data : in String) return String;
-- Create the decoder object for the specified encoding format.
function Create (Name : in String) return Decoder;
-- ------------------------------
-- Stream Transformation interface
-- ------------------------------
-- The <b>Transformer</b> interface defines the operation to transform
-- a stream from one data format to another.
type Transformer is limited interface;
type Transformer_Access is access all Transformer'Class;
-- Transform the input array represented by <b>Data</b> into
-- the output array <b>Into</b>. The transformation made by
-- the object can be of any nature (Hex encoding, Base64 encoding,
-- Hex decoding, Base64 decoding, encryption, compression, ...).
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> array.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output array <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- array cannot be transformed.
procedure Transform (E : in out Transformer;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Finish encoding the input array.
procedure Finish (E : in out Transformer;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset) is null;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in String) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer.
--
-- Returns the transformed string.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
function Transform (E : in out Transformer'Class;
Data : in Ada.Streams.Stream_Element_Array) return String;
-- Transform the input string <b>Data</b> using the transformation
-- rules provided by the <b>E</b> transformer and return the data in
-- the <b>Into</b> array, setting <b>Last</b> to the last index.
--
-- Raises the <b>Encoding_Error</b> exception if the source string
-- cannot be transformed
procedure Transform (E : in out Transformer'Class;
Data : in String;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting
-- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits
-- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated
-- to indicate the position of the last valid byte written in <tt>Into</tt>.
procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : in Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
-- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting
-- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated
-- to indicate the last position in the byte array.
procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array;
Pos : in Ada.Streams.Stream_Element_Offset;
Val : out Interfaces.Unsigned_64;
Last : out Ada.Streams.Stream_Element_Offset);
private
type Encoder is new Ada.Finalization.Limited_Controlled with record
Encode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Encoder);
type Decoder is new Ada.Finalization.Limited_Controlled with record
Decode : Transformer_Access := null;
end record;
-- Delete the transformers
overriding
procedure Finalize (E : in out Decoder);
end Util.Encoders;
|
Declare an Encode function that accepts a Stream_Element_Array as parameter
|
Declare an Encode function that accepts a Stream_Element_Array as parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9dd4e0fbf003ec6b7eaf1665930a0402f1372688
|
src/gen-model.ads
|
src/gen-model.ads
|
-----------------------------------------------------------------------
-- gen-model -- Model for Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Objects.Maps;
with DOM.Core;
package Gen.Model is
-- Exception raised if a name is already registered in the model.
-- This exception is raised if a table, an enum is already defined.
Name_Exist : exception;
-- ------------------------------
-- Model Definition
-- ------------------------------
type Definition is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with record
Row_Index : Natural;
Name : Ada.Strings.Unbounded.Unbounded_String;
Attrs : Util.Beans.Objects.Maps.Map_Bean;
Comment : Util.Beans.Objects.Object;
end record;
type Definition_Access is access all Definition'Class;
-- Prepare the generation of the model.
procedure Prepare (O : in out Definition) is null;
-- Get the object unique name.
function Get_Name (From : in Definition) return String;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Attribute (From : in Definition;
Name : in String) return String;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Attribute (From : in Definition;
Name : in String) return Ada.Strings.Unbounded.Unbounded_String;
-- Set the comment associated with the element.
procedure Set_Comment (Def : in out Definition;
Comment : in String);
-- Initialize the definition from the DOM node attributes.
procedure Initialize (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Node : in DOM.Core.Node);
end Gen.Model;
|
-----------------------------------------------------------------------
-- gen-model -- Model for Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 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.Finalization;
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Objects.Maps;
with DOM.Core;
package Gen.Model is
-- Exception raised if a name is already registered in the model.
-- This exception is raised if a table, an enum is already defined.
Name_Exist : exception;
-- ------------------------------
-- Model Definition
-- ------------------------------
type Definition is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with private;
type Definition_Access is access all Definition'Class;
-- Prepare the generation of the model.
procedure Prepare (O : in out Definition) is null;
-- Get the object unique name.
function Get_Name (From : in Definition) return String;
function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String;
-- Set the object unique name.
procedure Set_Name (Def : in out Definition;
Name : in String);
procedure Set_Name (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String);
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Attribute (From : in Definition;
Name : in String) return String;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Attribute (From : in Definition;
Name : in String) return Ada.Strings.Unbounded.Unbounded_String;
-- Set the comment associated with the element.
procedure Set_Comment (Def : in out Definition;
Comment : in String);
-- Get the comment associated with the element.
function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object;
-- Set the location (file and line) where the model element is defined in the XMI file.
procedure Set_Location (Node : in out Definition;
Location : in String);
-- Get the location file and line where the model element is defined.
function Get_Location (Node : in Definition) return String;
-- Initialize the definition from the DOM node attributes.
procedure Initialize (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Node : in DOM.Core.Node);
private
type Definition is new Ada.Finalization.Limited_Controlled
and Util.Beans.Basic.Readonly_Bean with record
Row_Index : Natural;
Def_Name : Ada.Strings.Unbounded.Unbounded_String;
Attrs : Util.Beans.Objects.Maps.Map_Bean;
Comment : Util.Beans.Objects.Object;
Location : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Gen.Model;
|
Make the Definition type private Add Set_Name, Get_Comment, Get_Location, Set_Location operations
|
Make the Definition type private
Add Set_Name, Get_Comment, Get_Location, Set_Location operations
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
74f4071f8cacf6671e0387d5beaa133e5b7a2927
|
src/asf-components-ajax-factory.ads
|
src/asf-components-ajax-factory.ads
|
-----------------------------------------------------------------------
-- components-ajax-factory -- Factory for AJAX Components
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Factory;
package ASF.Components.Ajax.Factory is
use ASF;
-- Get the Ajax component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
end ASF.Components.Ajax.Factory;
|
-----------------------------------------------------------------------
-- components-ajax-factory -- Factory for AJAX Components
-- Copyright (C) 2011, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Factory;
package ASF.Components.Ajax.Factory is
-- Register the Ajax component factory.
procedure Register (Factory : in out ASF.Factory.Component_Factory);
end ASF.Components.Ajax.Factory;
|
Change the Definition function into a Register procedure
|
Change the Definition function into a Register procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
76034819cbb5914e803c44162cfcc992205e942b
|
awa/plugins/awa-storages/src/awa-storages-servlets.ads
|
awa/plugins/awa-storages/src/awa-storages-servlets.ads
|
-----------------------------------------------------------------------
-- awa-storages-servlets -- Serve files saved in the storage service
-- Copyright (C) 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 Ada.Calendar;
with Servlet.Core;
with ASF.Requests;
with ASF.Responses;
-- == Storage Servlet ==
-- The <tt>Storage_Servlet</tt> type is the servlet that allows to retrieve the file
-- content that was uploaded.
package AWA.Storages.Servlets is
-- The <b>Storage_Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Storage_Servlet is new Servlet.Core.Servlet with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Storage_Servlet;
Context : in Servlet.Core.Servlet_Registry'Class);
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
overriding
procedure Do_Get (Server : in Storage_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
procedure Load (Server : in Storage_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref);
private
type Storage_Servlet is new Servlet.Core.Servlet with null record;
end AWA.Storages.Servlets;
|
-----------------------------------------------------------------------
-- awa-storages-servlets -- Serve files saved in the storage service
-- Copyright (C) 2012, 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 Ada.Calendar;
with Servlet.Core;
with ASF.Requests;
with ASF.Responses;
-- == Storage Servlet ==
-- The <tt>Storage_Servlet</tt> type is the servlet that allows to retrieve the file
-- content that was uploaded.
package AWA.Storages.Servlets is
type Get_Type is (DEFAULT, AS_CONTENT_DISPOSITION, INVALID);
-- The <b>Storage_Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Storage_Servlet is new Servlet.Core.Servlet with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Storage_Servlet;
Context : in Servlet.Core.Servlet_Registry'Class);
-- Called by the server (via the service method) to allow a servlet to handle
-- a GET request.
--
-- Overriding this method to support a GET request also automatically supports
-- an HTTP HEAD request. A HEAD request is a GET request that returns no body
-- in the response, only the request header fields.
--
-- When overriding this method, read the request data, write the response headers,
-- get the response's writer or output stream object, and finally, write the
-- response data. It's best to include content type and encoding.
-- When using a PrintWriter object to return the response, set the content type
-- before accessing the PrintWriter object.
--
-- The servlet container must write the headers before committing the response,
-- because in HTTP the headers must be sent before the response body.
--
-- Where possible, set the Content-Length header (with the
-- Response.Set_Content_Length method), to allow the servlet container
-- to use a persistent connection to return its response to the client,
-- improving performance. The content length is automatically set if the entire
-- response fits inside the response buffer.
--
-- When using HTTP 1.1 chunked encoding (which means that the response has a
-- Transfer-Encoding header), do not set the Content-Length header.
--
-- The GET method should be safe, that is, without any side effects for which
-- users are held responsible. For example, most form queries have no side effects.
-- If a client request is intended to change stored data, the request should use
-- some other HTTP method.
--
-- The GET method should also be idempotent, meaning that it can be safely repeated.
-- Sometimes making a method safe also makes it idempotent. For example, repeating
-- queries is both safe and idempotent, but buying a product online or modifying
-- data is neither safe nor idempotent.
--
-- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request"
overriding
procedure Do_Get (Server : in Storage_Servlet;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class);
-- Load the data content that correspond to the GET request and get the name as well
-- as mime-type and date.
procedure Load (Server : in Storage_Servlet;
Request : in out ASF.Requests.Request'Class;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Data : out ADO.Blob_Ref);
-- Get the expected return mode (content disposition for download or inline).
function Get_Format (Server : in Storage_Servlet;
Request : in ASF.Requests.Request'Class) return Get_Type;
private
type Storage_Servlet is new Servlet.Core.Servlet with null record;
end AWA.Storages.Servlets;
|
Declare the Get_Format function on the Storage_Servlet
|
Declare the Get_Format function on the Storage_Servlet
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a8bd1de519fefb9c317c7cbfa03246ab9047890e
|
src/asf-components-widgets-factory.adb
|
src/asf-components-widgets-factory.adb
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
with ASF.Components.Widgets.Likes;
with ASF.Components.Widgets.Panels;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
function Create_Like return UIComponent_Access;
function Create_Panel return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
-- ------------------------------
-- Create a UILike component
-- ------------------------------
function Create_Like return UIComponent_Access is
begin
return new ASF.Components.Widgets.Likes.UILike;
end Create_Like;
-- ------------------------------
-- Create a UIPanel component
-- ------------------------------
function Create_Panel return UIComponent_Access is
begin
return new ASF.Components.Widgets.Panels.UIPanel;
end Create_Panel;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
LIKE_TAG : aliased constant String := "like";
PANEL_TAG : aliased constant String := "panel";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_DATE_TAG'Access,
Component => Create_Input_Date'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => GRAVATAR_TAG'Access,
Component => Create_Gravatar'Access,
Tag => Create_Component_Node'Access),
5 => (Name => LIKE_TAG'Access,
Component => Create_Like'Access,
Tag => Create_Component_Node'Access),
6 => (Name => PANEL_TAG'Access,
Component => Create_Panel'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Views.Nodes;
with ASF.Components.Base;
with ASF.Components.Widgets.Inputs;
with ASF.Components.Widgets.Gravatars;
with ASF.Components.Widgets.Likes;
with ASF.Components.Widgets.Panels;
with ASF.Components.Widgets.Tabs;
package body ASF.Components.Widgets.Factory is
use ASF.Components.Base;
function Create_Input return UIComponent_Access;
function Create_Input_Date return UIComponent_Access;
function Create_Complete return UIComponent_Access;
function Create_Gravatar return UIComponent_Access;
function Create_Like return UIComponent_Access;
function Create_Panel return UIComponent_Access;
function Create_TabView return UIComponent_Access;
function Create_Tab return UIComponent_Access;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInput;
end Create_Input;
-- ------------------------------
-- Create a UIInput component
-- ------------------------------
function Create_Input_Date return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIInputDate;
end Create_Input_Date;
-- ------------------------------
-- Create a UIComplete component
-- ------------------------------
function Create_Complete return UIComponent_Access is
begin
return new ASF.Components.Widgets.Inputs.UIComplete;
end Create_Complete;
-- ------------------------------
-- Create a UIGravatar component
-- ------------------------------
function Create_Gravatar return UIComponent_Access is
begin
return new ASF.Components.Widgets.Gravatars.UIGravatar;
end Create_Gravatar;
-- ------------------------------
-- Create a UILike component
-- ------------------------------
function Create_Like return UIComponent_Access is
begin
return new ASF.Components.Widgets.Likes.UILike;
end Create_Like;
-- ------------------------------
-- Create a UIPanel component
-- ------------------------------
function Create_Panel return UIComponent_Access is
begin
return new ASF.Components.Widgets.Panels.UIPanel;
end Create_Panel;
-- ------------------------------
-- Create a UITab component
-- ------------------------------
function Create_Tab return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UITab;
end Create_Tab;
-- ------------------------------
-- Create a UITabView component
-- ------------------------------
function Create_TabView return UIComponent_Access is
begin
return new ASF.Components.Widgets.Tabs.UITabView;
end Create_TabView;
use ASF.Views.Nodes;
URI : aliased constant String := "http://code.google.com/p/ada-asf/widget";
AUTOCOMPLETE_TAG : aliased constant String := "autocomplete";
INPUT_DATE_TAG : aliased constant String := "inputDate";
INPUT_TEXT_TAG : aliased constant String := "inputText";
GRAVATAR_TAG : aliased constant String := "gravatar";
LIKE_TAG : aliased constant String := "like";
PANEL_TAG : aliased constant String := "panel";
TAB_TAG : aliased constant String := "tab";
TAB_VIEW_TAG : aliased constant String := "tabView";
Widget_Bindings : aliased constant ASF.Factory.Binding_Array
:= (1 => (Name => AUTOCOMPLETE_TAG'Access,
Component => Create_Complete'Access,
Tag => Create_Component_Node'Access),
2 => (Name => INPUT_DATE_TAG'Access,
Component => Create_Input_Date'Access,
Tag => Create_Component_Node'Access),
3 => (Name => INPUT_TEXT_TAG'Access,
Component => Create_Input'Access,
Tag => Create_Component_Node'Access),
4 => (Name => GRAVATAR_TAG'Access,
Component => Create_Gravatar'Access,
Tag => Create_Component_Node'Access),
5 => (Name => LIKE_TAG'Access,
Component => Create_Like'Access,
Tag => Create_Component_Node'Access),
6 => (Name => PANEL_TAG'Access,
Component => Create_Panel'Access,
Tag => Create_Component_Node'Access),
7 => (Name => TAB_TAG'Access,
Component => Create_Tab'Access,
Tag => Create_Component_Node'Access),
8 => (Name => TAB_VIEW_TAG'Access,
Component => Create_TabView'Access,
Tag => Create_Component_Node'Access)
);
Core_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Widget_Bindings'Access);
-- ------------------------------
-- Get the widget component factory.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Core_Factory'Access;
end Definition;
end ASF.Components.Widgets.Factory;
|
Add the new <w:tab> and <w:tabView> components in the factory
|
Add the new <w:tab> and <w:tabView> components in the factory
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
4e7742ef03e55d534bdce6f99eeafa3b32b34c9f
|
testutil/ahven/ahven-xml_runner.adb
|
testutil/ahven/ahven-xml_runner.adb
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <[email protected]>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Text_IO;
with Ada.Strings;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Ahven.Runner;
with Ahven_Compat;
with Ahven.AStrings;
package body Ahven.XML_Runner is
use Ada.Text_IO;
use Ada.Strings.Fixed;
use Ada.Strings.Maps;
use Ahven.Results;
use Ahven.Framework;
use Ahven.AStrings;
function Filter_String (Str : String) return String;
function Filter_String
(Str : String;
Map : Character_Mapping)
return String;
procedure Print_Test_Pass (File : File_Type;
Parent_Test : String;
Info : Result_Info);
procedure Print_Test_Failure (File : File_Type;
Parent_Test : String;
Info : Result_Info);
procedure Print_Test_Error (File : File_Type;
Parent_Test : String;
Info : Result_Info);
procedure Print_Test_Case (Collection : Result_Collection;
Dir : String);
procedure Print_Log_File (File : File_Type; Filename : String);
procedure Print_Attribute (File : File_Type; Attr : String;
Value : String);
procedure Start_Testcase_Tag (File : File_Type;
Parent : String; Name : String;
Execution_Time : String);
procedure End_Testcase_Tag (File : File_Type);
function Create_Name (Dir : String; Name : String) return String;
function Filter_String (Str : String) return String is
Result : String (Str'First .. Str'First + 6 * Str'Length);
Pos : Natural := Str'First;
begin
for I in Str'Range loop
if Str (I) = ''' then
Result (Pos .. Pos + 6 - 1) := "'";
Pos := Pos + 6;
elsif Str (I) = '<' then
Result (Pos .. Pos + 4 - 1) := "<";
Pos := Pos + 4;
elsif Str (I) = '>' then
Result (Pos .. Pos + 4 - 1) := ">";
Pos := Pos + 4;
elsif Str (I) = '&' then
Result (Pos .. Pos + 5 - 1) := "&";
Pos := Pos + 5;
else
Result (Pos) := Str (I);
Pos := Pos + 1;
end if;
end loop;
return Result (Result'First .. Pos - 1);
end Filter_String;
function Filter_String
(Str : String;
Map : Character_Mapping)
return String
is
begin
return Translate (Source => Str,
Mapping => Map);
end Filter_String;
procedure Print_Attribute (File : File_Type; Attr : String;
Value : String) is
begin
Put (File, Attr & "=" & '"' & Value & '"');
end Print_Attribute;
procedure Start_Testcase_Tag (File : File_Type;
Parent : String; Name : String;
Execution_Time : String) is
begin
Put (File, "<testcase ");
Print_Attribute (File, "classname", Filter_String (Parent));
Put (File, " ");
Print_Attribute (File, "name", Filter_String (Name));
Put (File, " ");
Print_Attribute (File, "time", Filter_String (Execution_Time));
Put_Line (File, ">");
end Start_Testcase_Tag;
procedure End_Testcase_Tag (File : File_Type) is
begin
Put_Line (File, "</testcase>");
end End_Testcase_Tag;
function Create_Name (Dir : String; Name : String) return String
is
function Filename (Test : String) return String is
Map : Ada.Strings.Maps.Character_Mapping;
begin
Map := To_Mapping (From => " '/\<>:|?*()" & '"',
To => "-___________" & '_');
return "TEST-" & Filter_String (Test, Map) & ".xml";
end Filename;
begin
if Dir'Length > 0 then
return Dir & Ahven_Compat.Directory_Separator & Filename (Name);
else
return Filename (Name);
end if;
end Create_Name;
procedure Print_Test_Pass (File : File_Type;
Parent_Test : String;
Info : Result_Info) is
Exec_Time : constant String :=
Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both);
begin
Start_Testcase_Tag
(File => File,
Parent => Parent_Test,
Name => Get_Routine_Name (Info),
Execution_Time => Exec_Time);
if Length (Get_Output_File (Info)) > 0 then
Put (File, "<system-out>");
Print_Log_File (File, To_String (Get_Output_File (Info)));
Put_Line (File, "</system-out>");
end if;
End_Testcase_Tag (File);
end Print_Test_Pass;
procedure Print_Test_Skipped (File : File_Type;
Parent_Test : String;
Info : Result_Info) is
Exec_Time : constant String :=
Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both);
begin
Start_Testcase_Tag
(File => File,
Parent => Parent_Test,
Name => Get_Routine_Name (Info),
Execution_Time => Exec_Time);
Put (File, "<skipped ");
Print_Attribute (File, "message",
Trim (Get_Message (Info), Ada.Strings.Both));
Put (File, ">");
Put_Line (File, Get_Message (Info));
Put_Line (File, "</skipped>");
End_Testcase_Tag (File);
end Print_Test_Skipped;
procedure Print_Test_Failure (File : File_Type;
Parent_Test : String;
Info : Result_Info) is
Exec_Time : constant String :=
Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both);
begin
Start_Testcase_Tag
(File => File,
Parent => Parent_Test,
Name => Get_Routine_Name (Info),
Execution_Time => Exec_Time);
Put (File, "<failure ");
Print_Attribute (File, "type",
Trim (Get_Message (Info), Ada.Strings.Both));
Put (File, ">");
Put_Line (File, Get_Message (Info));
Put_Line (File, "</failure>");
if Length (Get_Output_File (Info)) > 0 then
Put (File, "<system-out>");
Print_Log_File (File, To_String (Get_Output_File (Info)));
Put_Line (File, "</system-out>");
end if;
End_Testcase_Tag (File);
end Print_Test_Failure;
procedure Print_Test_Error (File : File_Type;
Parent_Test : String;
Info : Result_Info) is
Exec_Time : constant String :=
Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both);
begin
Start_Testcase_Tag
(File => File,
Parent => Parent_Test,
Name => Get_Routine_Name (Info),
Execution_Time => Exec_Time);
Put (File, "<error ");
Print_Attribute (File, "type",
Trim (Get_Message (Info), Ada.Strings.Both));
Put (File, ">");
Put_Line (File, Get_Message (Info));
Put_Line (File, "</error>");
if Length (Get_Output_File (Info)) > 0 then
Put (File, "<system-out>");
Print_Log_File (File, To_String (Get_Output_File (Info)));
Put_Line (File, "</system-out>");
end if;
End_Testcase_Tag (File);
end Print_Test_Error;
procedure Print_Test_Case (Collection : Result_Collection;
Dir : String) is
procedure Print (Output : File_Type;
Result : Result_Collection);
-- Internal procedure to print the testcase into given file.
function Img (Value : Natural) return String is
begin
return Trim (Natural'Image (Value), Ada.Strings.Both);
end Img;
procedure Print (Output : File_Type;
Result : Result_Collection) is
Position : Result_Info_Cursor;
begin
Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' &
" encoding=" & '"' & "iso-8859-1" & '"' &
"?>");
Put (Output, "<testsuite ");
Print_Attribute (Output, "errors", Img (Error_Count (Result)));
Put (Output, " ");
Print_Attribute (Output, "failures", Img (Failure_Count (Result)));
Put (Output, " ");
Print_Attribute (Output, "skips", Img (Skipped_Count (Result)));
Put (Output, " ");
Print_Attribute (Output, "tests", Img (Test_Count (Result)));
Put (Output, " ");
Print_Attribute (Output, "time",
Trim (Duration'Image (Get_Execution_Time (Result)),
Ada.Strings.Both));
Put (Output, " ");
Print_Attribute (Output,
"name", To_String (Get_Test_Name (Result)));
Put_Line (Output, ">");
Position := First_Error (Result);
Error_Loop:
loop
exit Error_Loop when not Is_Valid (Position);
Print_Test_Error (Output,
To_String (Get_Test_Name (Result)), Data (Position));
Position := Next (Position);
end loop Error_Loop;
Position := First_Failure (Result);
Failure_Loop:
loop
exit Failure_Loop when not Is_Valid (Position);
Print_Test_Failure (Output,
To_String (Get_Test_Name (Result)), Data (Position));
Position := Next (Position);
end loop Failure_Loop;
Position := First_Pass (Result);
Pass_Loop:
loop
exit Pass_Loop when not Is_Valid (Position);
Print_Test_Pass (Output,
To_String (Get_Test_Name (Result)), Data (Position));
Position := Next (Position);
end loop Pass_Loop;
Position := First_Skipped (Result);
Skip_Loop:
loop
exit Skip_Loop when not Is_Valid (Position);
Print_Test_Skipped (Output,
To_String (Get_Test_Name (Result)), Data (Position));
Position := Next (Position);
end loop Skip_Loop;
Put_Line (Output, "</testsuite>");
end Print;
File : File_Type;
begin
if Dir = "-" then
Print (Standard_Output, Collection);
else
Create (File => File, Mode => Ada.Text_IO.Out_File,
Name => Create_Name (Dir, To_String (Get_Test_Name (Collection))));
Print (File, Collection);
Ada.Text_IO.Close (File);
end if;
end Print_Test_Case;
procedure Report_Results (Result : Result_Collection;
Dir : String) is
Position : Result_Collection_Cursor;
begin
Position := First_Child (Result);
loop
exit when not Is_Valid (Position);
if Child_Depth (Data (Position).all) = 0 then
Print_Test_Case (Data (Position).all, Dir);
else
Report_Results (Data (Position).all, Dir);
-- Handle the test cases in this collection
if Direct_Test_Count (Result) > 0 then
Print_Test_Case (Result, Dir);
end if;
end if;
Position := Next (Position);
end loop;
end Report_Results;
-- Print the log by placing the data inside CDATA block.
procedure Print_Log_File (File : File_Type; Filename : String) is
type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET);
function State_Change (Old_State : CData_End_State)
return CData_End_State;
Handle : File_Type;
Char : Character := ' ';
First : Boolean := True;
-- We need to escape ]]>, this variable tracks
-- the characters, so we know when to do the escaping.
CData_Ending : CData_End_State := NONE;
function State_Change (Old_State : CData_End_State)
return CData_End_State
is
New_State : CData_End_State := NONE;
-- By default New_State will be NONE, so there is
-- no need to set it inside when blocks.
begin
case Old_State is
when NONE =>
if Char = ']' then
New_State := FIRST_BRACKET;
end if;
when FIRST_BRACKET =>
if Char = ']' then
New_State := SECOND_BRACKET;
end if;
when SECOND_BRACKET =>
if Char = '>' then
Put (File, " ");
end if;
end case;
return New_State;
end State_Change;
begin
Open (Handle, In_File, Filename);
loop
exit when End_Of_File (Handle);
Get (Handle, Char);
if First then
Put (File, "<![CDATA[");
First := False;
end if;
CData_Ending := State_Change (CData_Ending);
Put (File, Char);
if End_Of_Line (Handle) then
New_Line (File);
end if;
end loop;
Close (Handle);
if not First then
Put_Line (File, "]]>");
end if;
end Print_Log_File;
procedure Do_Report (Test_Results : Results.Result_Collection;
Args : Parameters.Parameter_Info) is
begin
Report_Results (Test_Results,
Parameters.Result_Dir (Args));
end Do_Report;
procedure Run (Suite : in out Framework.Test_Suite'Class) is
begin
Runner.Run_Suite (Suite, Do_Report'Access);
end Run;
procedure Run (Suite : Framework.Test_Suite_Access) is
begin
Run (Suite.all);
end Run;
end Ahven.XML_Runner;
|
--
-- Copyright (c) 2007-2009 Tero Koskinen <[email protected]>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Text_IO;
with Ada.Strings;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Ahven.Runner;
with Ahven_Compat;
with Ahven.AStrings;
package body Ahven.XML_Runner is
use Ada.Text_IO;
use Ada.Strings.Fixed;
use Ada.Strings.Maps;
use Ahven.Results;
use Ahven.Framework;
use Ahven.AStrings;
function Filter_String (Str : String) return String;
function Filter_String
(Str : String;
Map : Character_Mapping)
return String;
procedure Print_Test_Pass (File : File_Type;
Parent_Test : String;
Info : Result_Info);
procedure Print_Test_Failure (File : File_Type;
Parent_Test : String;
Info : Result_Info);
procedure Print_Test_Error (File : File_Type;
Parent_Test : String;
Info : Result_Info);
procedure Print_Test_Case (Collection : Result_Collection;
Dir : String);
procedure Print_Log_File (File : File_Type; Filename : String);
procedure Print_Attribute (File : File_Type; Attr : String;
Value : String);
procedure Start_Testcase_Tag (File : File_Type;
Parent : String; Name : String;
Execution_Time : String);
procedure End_Testcase_Tag (File : File_Type);
function Create_Name (Dir : String; Name : String) return String;
function Filter_String (Str : String) return String is
Result : String (Str'First .. Str'First + 6 * Str'Length);
Pos : Natural := Str'First;
begin
for I in Str'Range loop
if Str (I) = ''' then
Result (Pos .. Pos + 6 - 1) := "'";
Pos := Pos + 6;
elsif Str (I) = '<' then
Result (Pos .. Pos + 4 - 1) := "<";
Pos := Pos + 4;
elsif Str (I) = '>' then
Result (Pos .. Pos + 4 - 1) := ">";
Pos := Pos + 4;
elsif Str (I) = '&' then
Result (Pos .. Pos + 5 - 1) := "&";
Pos := Pos + 5;
else
Result (Pos) := Str (I);
Pos := Pos + 1;
end if;
end loop;
return Result (Result'First .. Pos - 1);
end Filter_String;
function Filter_String
(Str : String;
Map : Character_Mapping)
return String
is
begin
return Translate (Source => Str,
Mapping => Map);
end Filter_String;
procedure Print_Attribute (File : File_Type; Attr : String;
Value : String) is
begin
Put (File, Attr & "=" & '"' & Value & '"');
end Print_Attribute;
procedure Start_Testcase_Tag (File : File_Type;
Parent : String; Name : String;
Execution_Time : String) is
begin
Put (File, "<testcase ");
Print_Attribute (File, "classname", Filter_String (Parent));
Put (File, " ");
Print_Attribute (File, "name", Filter_String (Name));
Put (File, " ");
Print_Attribute (File, "time", Filter_String (Execution_Time));
Put_Line (File, ">");
end Start_Testcase_Tag;
procedure End_Testcase_Tag (File : File_Type) is
begin
Put_Line (File, "</testcase>");
end End_Testcase_Tag;
function Create_Name (Dir : String; Name : String) return String
is
function Filename (Test : String) return String is
Map : Ada.Strings.Maps.Character_Mapping;
begin
Map := To_Mapping (From => " '/\<>:|?*()" & '"',
To => "-___________" & '_');
return "TEST-" & Filter_String (Test, Map) & ".xml";
end Filename;
begin
if Dir'Length > 0 then
return Dir & Ahven_Compat.Directory_Separator & Filename (Name);
else
return Filename (Name);
end if;
end Create_Name;
procedure Print_Test_Pass (File : File_Type;
Parent_Test : String;
Info : Result_Info) is
Exec_Time : constant String :=
Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both);
begin
Start_Testcase_Tag
(File => File,
Parent => Parent_Test,
Name => Get_Routine_Name (Info),
Execution_Time => Exec_Time);
if Length (Get_Output_File (Info)) > 0 then
Put (File, "<system-out>");
Print_Log_File (File, To_String (Get_Output_File (Info)));
Put_Line (File, "</system-out>");
end if;
End_Testcase_Tag (File);
end Print_Test_Pass;
procedure Print_Test_Skipped (File : File_Type;
Parent_Test : String;
Info : Result_Info) is
Exec_Time : constant String :=
Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both);
begin
Start_Testcase_Tag
(File => File,
Parent => Parent_Test,
Name => Get_Routine_Name (Info),
Execution_Time => Exec_Time);
Put (File, "<skipped ");
Print_Attribute (File, "message",
Filter_String (Trim (Get_Message (Info), Ada.Strings.Both)));
Put (File, ">");
Put_Line (File, Get_Message (Info));
Put_Line (File, "</skipped>");
End_Testcase_Tag (File);
end Print_Test_Skipped;
procedure Print_Test_Failure (File : File_Type;
Parent_Test : String;
Info : Result_Info) is
Exec_Time : constant String :=
Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both);
begin
Start_Testcase_Tag
(File => File,
Parent => Parent_Test,
Name => Get_Routine_Name (Info),
Execution_Time => Exec_Time);
Put (File, "<failure ");
Print_Attribute (File, "type",
Filter_String (Trim (Get_Message (Info), Ada.Strings.Both)));
Put (File, ">");
Put_Line (File, Get_Message (Info));
Put_Line (File, "</failure>");
if Length (Get_Output_File (Info)) > 0 then
Put (File, "<system-out>");
Print_Log_File (File, To_String (Get_Output_File (Info)));
Put_Line (File, "</system-out>");
end if;
End_Testcase_Tag (File);
end Print_Test_Failure;
procedure Print_Test_Error (File : File_Type;
Parent_Test : String;
Info : Result_Info) is
Exec_Time : constant String :=
Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both);
begin
Start_Testcase_Tag
(File => File,
Parent => Parent_Test,
Name => Get_Routine_Name (Info),
Execution_Time => Exec_Time);
Put (File, "<error ");
Print_Attribute (File, "type",
Trim (Get_Message (Info), Ada.Strings.Both));
Put (File, ">");
Put_Line (File, Get_Message (Info));
Put_Line (File, "</error>");
if Length (Get_Output_File (Info)) > 0 then
Put (File, "<system-out>");
Print_Log_File (File, To_String (Get_Output_File (Info)));
Put_Line (File, "</system-out>");
end if;
End_Testcase_Tag (File);
end Print_Test_Error;
procedure Print_Test_Case (Collection : Result_Collection;
Dir : String) is
procedure Print (Output : File_Type;
Result : Result_Collection);
-- Internal procedure to print the testcase into given file.
function Img (Value : Natural) return String is
begin
return Trim (Natural'Image (Value), Ada.Strings.Both);
end Img;
procedure Print (Output : File_Type;
Result : Result_Collection) is
Position : Result_Info_Cursor;
begin
Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' &
" encoding=" & '"' & "iso-8859-1" & '"' &
"?>");
Put (Output, "<testsuite ");
Print_Attribute (Output, "errors", Img (Error_Count (Result)));
Put (Output, " ");
Print_Attribute (Output, "failures", Img (Failure_Count (Result)));
Put (Output, " ");
Print_Attribute (Output, "skips", Img (Skipped_Count (Result)));
Put (Output, " ");
Print_Attribute (Output, "tests", Img (Test_Count (Result)));
Put (Output, " ");
Print_Attribute (Output, "time",
Trim (Duration'Image (Get_Execution_Time (Result)),
Ada.Strings.Both));
Put (Output, " ");
Print_Attribute (Output,
"name", To_String (Get_Test_Name (Result)));
Put_Line (Output, ">");
Position := First_Error (Result);
Error_Loop:
loop
exit Error_Loop when not Is_Valid (Position);
Print_Test_Error (Output,
To_String (Get_Test_Name (Result)), Data (Position));
Position := Next (Position);
end loop Error_Loop;
Position := First_Failure (Result);
Failure_Loop:
loop
exit Failure_Loop when not Is_Valid (Position);
Print_Test_Failure (Output,
To_String (Get_Test_Name (Result)), Data (Position));
Position := Next (Position);
end loop Failure_Loop;
Position := First_Pass (Result);
Pass_Loop:
loop
exit Pass_Loop when not Is_Valid (Position);
Print_Test_Pass (Output,
To_String (Get_Test_Name (Result)), Data (Position));
Position := Next (Position);
end loop Pass_Loop;
Position := First_Skipped (Result);
Skip_Loop:
loop
exit Skip_Loop when not Is_Valid (Position);
Print_Test_Skipped (Output,
To_String (Get_Test_Name (Result)), Data (Position));
Position := Next (Position);
end loop Skip_Loop;
Put_Line (Output, "</testsuite>");
end Print;
File : File_Type;
begin
if Dir = "-" then
Print (Standard_Output, Collection);
else
Create (File => File, Mode => Ada.Text_IO.Out_File,
Name => Create_Name (Dir, To_String (Get_Test_Name (Collection))));
Print (File, Collection);
Ada.Text_IO.Close (File);
end if;
end Print_Test_Case;
procedure Report_Results (Result : Result_Collection;
Dir : String) is
Position : Result_Collection_Cursor;
begin
Position := First_Child (Result);
loop
exit when not Is_Valid (Position);
if Child_Depth (Data (Position).all) = 0 then
Print_Test_Case (Data (Position).all, Dir);
else
Report_Results (Data (Position).all, Dir);
-- Handle the test cases in this collection
if Direct_Test_Count (Result) > 0 then
Print_Test_Case (Result, Dir);
end if;
end if;
Position := Next (Position);
end loop;
end Report_Results;
-- Print the log by placing the data inside CDATA block.
procedure Print_Log_File (File : File_Type; Filename : String) is
type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET);
function State_Change (Old_State : CData_End_State)
return CData_End_State;
Handle : File_Type;
Char : Character := ' ';
First : Boolean := True;
-- We need to escape ]]>, this variable tracks
-- the characters, so we know when to do the escaping.
CData_Ending : CData_End_State := NONE;
function State_Change (Old_State : CData_End_State)
return CData_End_State
is
New_State : CData_End_State := NONE;
-- By default New_State will be NONE, so there is
-- no need to set it inside when blocks.
begin
case Old_State is
when NONE =>
if Char = ']' then
New_State := FIRST_BRACKET;
end if;
when FIRST_BRACKET =>
if Char = ']' then
New_State := SECOND_BRACKET;
end if;
when SECOND_BRACKET =>
if Char = '>' then
Put (File, " ");
end if;
end case;
return New_State;
end State_Change;
begin
Open (Handle, In_File, Filename);
loop
exit when End_Of_File (Handle);
Get (Handle, Char);
if First then
Put (File, "<![CDATA[");
First := False;
end if;
CData_Ending := State_Change (CData_Ending);
Put (File, Char);
if End_Of_Line (Handle) then
New_Line (File);
end if;
end loop;
Close (Handle);
if not First then
Put_Line (File, "]]>");
end if;
end Print_Log_File;
procedure Do_Report (Test_Results : Results.Result_Collection;
Args : Parameters.Parameter_Info) is
begin
Report_Results (Test_Results,
Parameters.Result_Dir (Args));
end Do_Report;
procedure Run (Suite : in out Framework.Test_Suite'Class) is
begin
Runner.Run_Suite (Suite, Do_Report'Access);
end Run;
procedure Run (Suite : Framework.Test_Suite_Access) is
begin
Run (Suite.all);
end Run;
end Ahven.XML_Runner;
|
Fix XML generation if a message contains < or >
|
Fix XML generation if a message contains < or >
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
5ba6c1d6679cdf6e8fd709a758a41bbfe4be0594
|
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
|
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-modules-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with ASF.Contexts.Faces;
with ASF.Contexts.Faces.Mockup;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Votes.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Delete_Question",
Test_Delete_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean",
Test_Question_Vote'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)",
Test_Question_Vote'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Module;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test deletion of a question.
-- ------------------------------
procedure Test_Delete_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Module;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I search strings in Ada?");
Q.Set_Description ("I have two strings that I want to search. % does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
T.Manager.Delete_Question (Q);
end Test_Delete_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
-- ------------------------------
-- Do a vote on a question through the question vote bean.
-- ------------------------------
procedure Do_Vote (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Vote : AWA.Votes.Beans.Vote_Bean_Access;
begin
Context.Set_Parameter ("id", "1");
Bean := Context.Get_Bean ("questionVote");
T.Assert (Bean /= null, "The questionVote bean was not created");
T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class,
"The questionVote is not a Vote_Bean");
Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access;
Vote.Rating := 1;
Vote.Entity_Id := 1;
Vote.Vote_Up (Outcome);
end Do_Vote;
-- ------------------------------
-- Test anonymous user voting for a question.
-- ------------------------------
procedure Test_Question_Vote_Anonymous (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Do_Vote (T);
T.Fail ("Anonymous users should not be allowed to vote");
exception
when AWA.Permissions.NO_PERMISSION =>
null;
end Test_Question_Vote_Anonymous;
-- ------------------------------
-- Test voting for a question.
-- ------------------------------
procedure Test_Question_Vote (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Do_Vote (T);
end Test_Question_Vote;
end AWA.Questions.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-modules-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Security.Contexts;
with ASF.Contexts.Faces;
with ASF.Contexts.Faces.Mockup;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Votes.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Delete_Question",
Test_Delete_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean",
Test_Question_Vote'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)",
Test_Question_Vote'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Module;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test deletion of a question.
-- ------------------------------
procedure Test_Delete_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Module;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I search strings in Ada?");
Q.Set_Description ("I have two strings that I want to search. % does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
T.Manager.Delete_Question (Q);
end Test_Delete_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
-- ------------------------------
-- Do a vote on a question through the question vote bean.
-- ------------------------------
procedure Do_Vote (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Vote : AWA.Votes.Beans.Vote_Bean_Access;
begin
Context.Set_Parameter ("id", "1");
Bean := Context.Get_Bean ("questionVote");
T.Assert (Bean /= null, "The questionVote bean was not created");
T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class,
"The questionVote is not a Vote_Bean");
Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access;
Vote.Rating := 1;
Vote.Entity_Id := 1;
Vote.Vote_Up (Outcome);
end Do_Vote;
-- ------------------------------
-- Test anonymous user voting for a question.
-- ------------------------------
procedure Test_Question_Vote_Anonymous (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Do_Vote (T);
T.Fail ("Anonymous users should not be allowed to vote");
exception
when AWA.Permissions.NO_PERMISSION =>
null;
end Test_Question_Vote_Anonymous;
-- ------------------------------
-- Test voting for a question.
-- ------------------------------
procedure Test_Question_Vote (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Do_Vote (T);
end Test_Question_Vote;
end AWA.Questions.Modules.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
78abb89bb9d400c67b9db4463db4079e2c17d2d1
|
src/sys/encoders/util-encoders-aes.ads
|
src/sys/encoders/util-encoders-aes.ads
|
-----------------------------------------------------------------------
-- util-encoders-aes -- AES encryption and decryption
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
private with Ada.Finalization;
-- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to
-- RFC3174 or [FIPS-180-1].
package Util.Encoders.AES is
type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR);
type Key_Type is private;
-- ------------------------------
-- ------------------------------
subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16);
AES_128_Length : constant := 16;
AES_192_Length : constant := 24;
AES_256_Length : constant := 32;
subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16);
subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24);
subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32);
type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32;
procedure Set_Encrypt_Key (Key : out Key_Type;
Data : in Secret_Key)
with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32;
procedure Set_Decrypt_Key (Key : out Key_Type;
Data : in Secret_Key)
with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32;
procedure Encrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array;
Output : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Key : in Key_Type);
procedure Decrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Decrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
type Cipher is tagged limited private;
-- Set the encryption initialization vector before starting the encryption.
procedure Set_IV (E : in out Cipher;
IV : in Word_Block_Type);
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Cipher and Util.Encoders.Transformer with private;
-- Set the encryption key to use.
procedure Set_Key (E : in out Encoder;
Data : in Secret_Key;
Mode : in AES_Mode := CBC);
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash 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);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Encoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset)
with Pre => Into'Length >= Block_Type'Length,
Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length;
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Decoder is new Cipher and Util.Encoders.Transformer with private;
-- Set the decryption key to use.
procedure Set_Key (E : in out Decoder;
Data : in Secret_Key;
Mode : in AES_Mode := CBC);
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash 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);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Decoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset);
private
use Interfaces;
type Block_Key is array (0 .. 59) of Unsigned_32;
type Key_Type is record
Key : Block_Key := (others => 0);
Rounds : Natural := 0;
end record;
type Cipher is limited new Ada.Finalization.Limited_Controlled with record
IV : Word_Block_Type;
Key : Key_Type;
Mode : AES_Mode := CBC;
Data_Count : Ada.Streams.Stream_Element_Offset := 0;
Data : Block_Type;
end record;
overriding
procedure Finalize (Object : in out Cipher);
type Encoder is new Cipher and Util.Encoders.Transformer with null record;
type Decoder is new Cipher and Util.Encoders.Transformer with null record;
end Util.Encoders.AES;
|
-----------------------------------------------------------------------
-- util-encoders-aes -- AES encryption and decryption
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
private with Ada.Finalization;
-- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to
-- RFC3174 or [FIPS-180-1].
package Util.Encoders.AES is
type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR);
type Key_Type is private;
-- ------------------------------
-- ------------------------------
subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16);
AES_128_Length : constant := 16;
AES_192_Length : constant := 24;
AES_256_Length : constant := 32;
subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16);
subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24);
subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32);
type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32;
procedure Set_Encrypt_Key (Key : out Key_Type;
Data : in Secret_Key)
with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32;
procedure Set_Decrypt_Key (Key : out Key_Type;
Data : in Secret_Key)
with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32;
procedure Encrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array;
Output : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Key : in Key_Type);
procedure Decrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Decrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
type Cipher is tagged limited private;
-- Set the encryption initialization vector before starting the encryption.
procedure Set_IV (E : in out Cipher;
IV : in Word_Block_Type);
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Cipher and Util.Encoders.Transformer with private;
-- Set the encryption key to use.
procedure Set_Key (E : in out Encoder;
Data : in Secret_Key;
Mode : in AES_Mode := CBC);
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash 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);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Encoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset)
with Pre => Into'Length >= Block_Type'Length,
Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length - 1;
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Decoder is new Cipher and Util.Encoders.Transformer with private;
-- Set the decryption key to use.
procedure Set_Key (E : in out Decoder;
Data : in Secret_Key;
Mode : in AES_Mode := CBC);
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash 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);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Decoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset);
private
use Interfaces;
type Block_Key is array (0 .. 59) of Unsigned_32;
type Key_Type is record
Key : Block_Key := (others => 0);
Rounds : Natural := 0;
end record;
type Cipher is limited new Ada.Finalization.Limited_Controlled with record
IV : Word_Block_Type;
Key : Key_Type;
Mode : AES_Mode := CBC;
Data_Count : Ada.Streams.Stream_Element_Offset := 0;
Data : Block_Type;
end record;
overriding
procedure Finalize (Object : in out Cipher);
type Encoder is new Cipher and Util.Encoders.Transformer with null record;
type Decoder is new Cipher and Util.Encoders.Transformer with null record;
end Util.Encoders.AES;
|
Fix post condition
|
Fix post condition
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
33602347ffe5ddef0f1cccf3ade386d0066c3dbe
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Events.Action_Method;
package body AWA.Workspaces.Beans is
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Bean.Module.Create_Workspace (WS);
end Create;
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017, 2018, 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 ASF.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Events.Action_Method;
package body AWA.Workspaces.Beans is
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Bean.Module.Create_Workspace (WS);
end Create;
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
Fix style warnings: add missing overriding and update and then/or else conditions
|
Fix style warnings: add missing overriding and update and then/or else conditions
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0318a2cd58c32978501c58e6e2b68a789e263f67
|
src/ado-sessions-factory.ads
|
src/ado-sessions-factory.ads
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sequences;
with ADO.Caches;
with ADO.Sessions.Sources;
-- === Session Factory ===
-- The session factory is the entry point to obtain a database session.
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
--
-- with ADO.Sessions.Factory;
-- ...
-- Sess_Factory : ADO.Sessions.Factory;
--
-- The session factory can be initialized by using the <tt>Create</tt> operation and
-- by giving a URI string that identifies the driver and the information to connect
-- to the database. The session factory is created only once when the application starts.
--
-- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test");
--
-- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or
-- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session
-- is returned. The session is released when the session variable is finalized.
--
-- DB : ADO.Sessions.Session := Sess_Factory.Get_Session;
--
-- The session factory is also responsible for maintaining some data that is shared by
-- all the database connections. This includes:
--
-- o the sequence generators used to allocate unique identifiers for database tables,
-- o the entity cache,
-- o some application specific global cache.
--
package ADO.Sessions.Factory is
pragma Elaborate_Body;
ENTITY_CACHE_NAME : constant String := "entity_type";
-- ------------------------------
-- 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.Sessions.Sources.Data_Source);
-- 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_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.Sessions.Sources.Data_Source;
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;
Cache : aliased ADO.Caches.Cache_Manager;
Cache_Values : ADO.Caches.Cache_Manager_Access;
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, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sequences;
with ADO.Caches;
with ADO.Sessions.Sources;
-- == Session Factory ==
-- The session factory is the entry point to obtain a database session.
-- The `ADO.Sessions.Factory` package defines the factory for creating
-- sessions.
--
-- with ADO.Sessions.Factory;
-- ...
-- Sess_Factory : ADO.Sessions.Factory;
--
-- The session factory can be initialized by using the `Create` operation and
-- by giving a URI string that identifies the driver and the information to connect
-- to the database. The session factory is created only once when the application starts.
--
-- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test");
--
-- Having a session factory, one can get a database by using the `Get_Session` or
-- `Get_Master_Session` function. Each time this operation is called, a new session
-- is returned. The session is released when the session variable is finalized.
--
-- DB : ADO.Sessions.Session := Sess_Factory.Get_Session;
--
-- The session factory is also responsible for maintaining some data that is shared by
-- all the database connections. This includes:
--
-- * the sequence generators used to allocate unique identifiers for database tables,
-- * the entity cache,
-- * some application specific global cache.
--
package ADO.Sessions.Factory is
pragma Elaborate_Body;
ENTITY_CACHE_NAME : constant String := "entity_type";
-- ------------------------------
-- 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.Sessions.Sources.Data_Source);
-- 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_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.Sessions.Sources.Data_Source;
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;
Cache : aliased ADO.Caches.Cache_Manager;
Cache_Values : ADO.Caches.Cache_Manager_Access;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
45dd826475b295f1f4e0403749cd9b26c527dae0
|
src/asf-validators-texts.ads
|
src/asf-validators-texts.ads
|
-----------------------------------------------------------------------
-- asf-validators-texts -- ASF Texts Validators
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Objects;
with ASF.Components.Base;
with ASF.Contexts.Faces;
-- The <b>ASF.Validators.Texts</b> defines various text oriented validators.
package ASF.Validators.Texts is
MAXIMUM_MESSAGE_ID : constant String := "asf.validators.length.maximum";
MINIMUM_MESSAGE_ID : constant String := "asf.validators.length.minimum";
-- ------------------------------
-- Length_Validator
-- ------------------------------
-- The <b>Length_Validator</b> implements the length validator whereby the given
-- value must have a minimum length and a maximum length.
type Length_Validator is new Validator with private;
type Length_Validator_Access is access all Length_Validator'Class;
-- Create a length validator.
function Create_Length_Validator (Minimum : in Natural;
Maximum : in Natural) return Validator_Access;
-- Verify that the value's length is between the validator minimum and maximum
-- boundaries.
-- If some error are found, the procedure should create a <b>FacesMessage</b>
-- describing the problem and add that message to the current faces context.
-- The procedure can examine the state and modify the component tree.
-- It must raise the <b>Invalid_Value</b> exception if the value is not valid.
procedure Validate (Valid : in Length_Validator;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Component : in out ASF.Components.Base.UIComponent'Class;
Value : in EL.Objects.Object);
private
type Length_Validator is new Validator with record
Minimum : Natural;
Maximum : Natural;
end record;
end ASF.Validators.Texts;
|
-----------------------------------------------------------------------
-- asf-validators-texts -- ASF Texts Validators
-- Copyright (C) 2011, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Regpat;
with EL.Objects;
with ASF.Components.Base;
with ASF.Contexts.Faces;
-- The <b>ASF.Validators.Texts</b> defines various text oriented validators.
package ASF.Validators.Texts is
MAXIMUM_MESSAGE_ID : constant String := "asf.validators.length.maximum";
MINIMUM_MESSAGE_ID : constant String := "asf.validators.length.minimum";
REGEX_MESSAGE_ID : constant String := "asf.validators.regex";
-- ------------------------------
-- Length_Validator
-- ------------------------------
-- The <b>Length_Validator</b> implements the length validator whereby the given
-- value must have a minimum length and a maximum length.
type Length_Validator is new Validator with private;
type Length_Validator_Access is access all Length_Validator'Class;
-- Create a length validator.
function Create_Length_Validator (Minimum : in Natural;
Maximum : in Natural) return Validator_Access;
-- Verify that the value's length is between the validator minimum and maximum
-- boundaries.
-- If some error are found, the procedure should create a <b>FacesMessage</b>
-- describing the problem and add that message to the current faces context.
-- The procedure can examine the state and modify the component tree.
-- It must raise the <b>Invalid_Value</b> exception if the value is not valid.
procedure Validate (Valid : in Length_Validator;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Component : in out ASF.Components.Base.UIComponent'Class;
Value : in EL.Objects.Object);
-- ------------------------------
-- Regex_Validator
-- ------------------------------
-- The <b>Regex_Validator</b> implements the regular expression validator
-- whereby the given value must match a regular expression.
type Regex_Validator (Size : GNAT.Regpat.Program_Size) is new Validator with private;
type Regex_Validator_Access is access all Regex_Validator'Class;
-- Create a regex validator.
function Create_Regex_Validator (Pattern : in GNAT.Regpat.Pattern_Matcher)
return Validator_Access;
-- Verify that the value matches the regular expression.
-- If some error are found, the procedure should create a <b>FacesMessage</b>
-- describing the problem and add that message to the current faces context.
-- The procedure can examine the state and modify the component tree.
-- It must raise the <b>Invalid_Value</b> exception if the value is not valid.
procedure Validate (Valid : in Regex_Validator;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Component : in out ASF.Components.Base.UIComponent'Class;
Value : in EL.Objects.Object);
private
type Length_Validator is new Validator with record
Minimum : Natural;
Maximum : Natural;
end record;
type Regex_Validator (Size : GNAT.Regpat.Program_Size) is new Validator with record
Pattern : GNAT.Regpat.Pattern_Matcher (Size);
end record;
end ASF.Validators.Texts;
|
Declare Regex_Validator to implement the JSF <f:validateRegex> tag
|
Declare Regex_Validator to implement the JSF <f:validateRegex> tag
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b3f70d127bfc7ef2c4a25881b4fe31d3b5b3a4e0
|
awa/plugins/awa-storages/src/awa-storages-stores-files.adb
|
awa/plugins/awa-storages/src/awa-storages-stores-files.adb
|
-----------------------------------------------------------------------
-- awa-storages-stores-files -- File system store
-- Copyright (C) 2012, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Directories;
with Interfaces;
with Util.Files;
with Util.Log.Loggers;
with Util.Encoders;
with Util.Encoders.Base64;
package body AWA.Storages.Stores.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Stores.Files");
-- ------------------------------
-- Create a file storage service and use the <tt>Root</tt> directory to store the files.
-- ------------------------------
function Create_File_Store (Root : in String) return Store_Access is
Result : constant File_Store_Access := new File_Store '(Len => Root'Length,
Root => Root);
begin
return Result.all'Access;
end Create_File_Store;
-- ------------------------------
-- Build a path where the file store represented by <tt>Store</tt> is saved.
-- ------------------------------
function Get_Path (Storage : in File_Store;
Store : in AWA.Storages.Models.Storage_Ref'Class) return String is
use Interfaces;
use type Ada.Streams.Stream_Element_Offset;
T : Util.Encoders.Base64.Encoder;
Buffer : Ada.Streams.Stream_Element_Array (1 .. 10);
R : Ada.Streams.Stream_Element_Array (1 .. 32);
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
Pos : Positive := 1;
Res : String (1 .. 16 + 5);
Workspace_Id : constant ADO.Identifier := Store.Get_Workspace.Get_Id;
begin
Util.Encoders.Encode_LEB128 (Buffer, Buffer'First, Unsigned_64 (Workspace_Id), Last);
Util.Encoders.Encode_LEB128 (Buffer, Last, Unsigned_64 (Store.Get_Id), Last);
T.Transform (Data => Buffer (1 .. Last),
Into => R, Last => Last,
Encoded => Encoded);
for I in 1 .. Last loop
Res (Pos) := Character'Val (R (I));
Pos := Pos + 1;
if (I mod 2) = 0 and I /= Last then
Res (Pos) := '/';
Pos := Pos + 1;
end if;
end loop;
return Util.Files.Compose (Storage.Root, Res (1 .. Pos - 1));
end Get_Path;
-- ------------------------------
-- Save the file represented by the `Path` variable into a store and associate that
-- content with the storage reference represented by `Into`.
-- ------------------------------
procedure Save (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is
pragma Unreferenced (Session);
Store : constant String := Storage.Get_Path (Into);
Dir : constant String := Ada.Directories.Containing_Directory (Store);
begin
Log.Info ("Storage save {0} to {1}", Path, Store);
Ada.Directories.Create_Path (Dir);
Ada.Directories.Copy_File (Source_Name => Path,
Target_Name => Store,
Form => "all");
end Save;
procedure Load (Storage : in File_Store;
Session : in out ADO.Sessions.Session'Class;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out Storage_File) is
pragma Unreferenced (Session);
Store : constant String := Storage.Get_Path (From);
begin
Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store);
end Load;
-- ------------------------------
-- Create a storage
-- ------------------------------
procedure Create (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File) is
pragma Unreferenced (Storage);
Store : constant String := Storage.Get_Path (From);
Dir : constant String := Ada.Directories.Containing_Directory (Store);
begin
Log.Info ("Storage create {0}", Store);
Ada.Directories.Create_Path (Dir);
Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store);
end Create;
-- ------------------------------
-- Delete the content associate with the storage represented by `From`.
-- ------------------------------
procedure Delete (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
From : in out AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Session);
Store : constant String := Storage.Get_Path (From);
begin
if Ada.Directories.Exists (Store) then
Log.Info ("Storage delete {0}", Store);
Ada.Directories.Delete_File (Store);
end if;
end Delete;
end AWA.Storages.Stores.Files;
|
-----------------------------------------------------------------------
-- awa-storages-stores-files -- File system store
-- Copyright (C) 2012, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Directories;
with Interfaces;
with Util.Files;
with Util.Log.Loggers;
with Util.Encoders;
with Util.Encoders.Base64;
package body AWA.Storages.Stores.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Stores.Files");
-- ------------------------------
-- Create a file storage service and use the <tt>Root</tt> directory to store the files.
-- ------------------------------
function Create_File_Store (Root : in String) return Store_Access is
Result : constant File_Store_Access := new File_Store '(Len => Root'Length,
Root => Root);
begin
return Result.all'Access;
end Create_File_Store;
-- ------------------------------
-- Build a path where the file store represented by <tt>Store</tt> is saved.
-- ------------------------------
function Get_Path (Storage : in File_Store;
Store : in AWA.Storages.Models.Storage_Ref'Class) return String is
begin
return Storage.Get_Path (Store.Get_Workspace.Get_Id, Store.Get_Id);
end Get_Path;
-- ------------------------------
-- Build a path where the file store represented by <tt>Store</tt> is saved.
-- ------------------------------
function Get_Path (Storage : in File_Store;
Workspace_Id : in ADO.Identifier;
File_Id : in ADO.Identifier) return String is
use Interfaces;
use type Ada.Streams.Stream_Element_Offset;
T : Util.Encoders.Base64.Encoder;
Buffer : Ada.Streams.Stream_Element_Array (1 .. 10);
R : Ada.Streams.Stream_Element_Array (1 .. 32);
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
Pos : Positive := 1;
Res : String (1 .. 16 + 5);
begin
Util.Encoders.Encode_LEB128 (Buffer, Buffer'First, Unsigned_64 (Workspace_Id), Last);
Util.Encoders.Encode_LEB128 (Buffer, Last, Unsigned_64 (File_Id), Last);
T.Transform (Data => Buffer (1 .. Last),
Into => R, Last => Last,
Encoded => Encoded);
for I in 1 .. Last loop
Res (Pos) := Character'Val (R (I));
Pos := Pos + 1;
if (I mod 2) = 0 and I /= Last then
Res (Pos) := '/';
Pos := Pos + 1;
end if;
end loop;
return Util.Files.Compose (Storage.Root, Res (1 .. Pos - 1));
end Get_Path;
-- ------------------------------
-- Save the file represented by the `Path` variable into a store and associate that
-- content with the storage reference represented by `Into`.
-- ------------------------------
procedure Save (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String) is
pragma Unreferenced (Session);
Store : constant String := Storage.Get_Path (Into);
Dir : constant String := Ada.Directories.Containing_Directory (Store);
begin
Log.Info ("Storage save {0} to {1}", Path, Store);
Ada.Directories.Create_Path (Dir);
Ada.Directories.Copy_File (Source_Name => Path,
Target_Name => Store,
Form => "all");
end Save;
procedure Load (Storage : in File_Store;
Session : in out ADO.Sessions.Session'Class;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out Storage_File) is
pragma Unreferenced (Session);
Store : constant String := Storage.Get_Path (From);
begin
Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store);
end Load;
-- ------------------------------
-- Create a storage
-- ------------------------------
procedure Create (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
From : in AWA.Storages.Models.Storage_Ref'Class;
Into : in out AWA.Storages.Storage_File) is
pragma Unreferenced (Storage);
Store : constant String := Storage.Get_Path (From);
Dir : constant String := Ada.Directories.Containing_Directory (Store);
begin
Log.Info ("Storage create {0}", Store);
Ada.Directories.Create_Path (Dir);
Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store);
end Create;
-- ------------------------------
-- Delete the content associate with the storage represented by `From`.
-- ------------------------------
procedure Delete (Storage : in File_Store;
Session : in out ADO.Sessions.Master_Session;
From : in out AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Session);
Store : constant String := Storage.Get_Path (From);
begin
if Ada.Directories.Exists (Store) then
Log.Info ("Storage delete {0}", Store);
Ada.Directories.Delete_File (Store);
end if;
end Delete;
end AWA.Storages.Stores.Files;
|
Implement new Get_Path function to build a temporary path
|
Implement new Get_Path function to build a temporary path
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a54ef28f1ba98cadc3572310adf2884a2aeb59c1
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.ads
|
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.ads
|
-----------------------------------------------------------------------
-- awa-votes-modules-tests -- Unit tests for vote service
-- 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.Tests;
with AWA.Tests;
package AWA.Votes.Modules.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Manager : AWA.Votes.Modules.Vote_Module_Access;
end record;
-- Test vote.
procedure Test_Vote_Up (T : in out Test);
end AWA.Votes.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-votes-modules-tests -- Unit tests for vote service
-- 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.Tests;
with AWA.Tests;
package AWA.Votes.Modules.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new AWA.Tests.Test with record
Manager : AWA.Votes.Modules.Vote_Module_Access;
end record;
-- Test vote.
procedure Test_Vote_Up (T : in out Test);
-- Test vote.
procedure Test_Vote_Undo (T : in out Test);
end AWA.Votes.Modules.Tests;
|
Add unit test for undo vote
|
Add unit test for undo vote
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3fec2203d9b5aca7358e64b3bee581f951004490
|
src/el-contexts-default.adb
|
src/el-contexts-default.adb
|
-----------------------------------------------------------------------
-- EL.Contexts -- Default contexts for evaluating an expression
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Variables;
with EL.Variables.Default;
package body EL.Contexts.Default is
-- ------------------------------
-- Retrieves the ELResolver associated with this ELcontext.
-- ------------------------------
overriding
function Get_Resolver (Context : Default_Context) return ELResolver_Access is
begin
return Context.Resolver;
end Get_Resolver;
-- ------------------------------
-- Set the ELResolver associated with this ELcontext.
-- ------------------------------
procedure Set_Resolver (Context : in out Default_Context;
Resolver : in ELResolver_Access) is
begin
Context.Resolver := Resolver;
end Set_Resolver;
-- ------------------------------
-- Retrieves the VariableMapper associated with this ELContext.
-- ------------------------------
overriding
function Get_Variable_Mapper (Context : Default_Context)
return access EL.Variables.VariableMapper'Class is
begin
return Context.Var_Mapper;
end Get_Variable_Mapper;
-- ------------------------------
-- Retrieves the FunctionMapper associated with this ELContext.
-- The FunctionMapper is only used when parsing an expression.
-- ------------------------------
overriding
function Get_Function_Mapper (Context : Default_Context)
return EL.Functions.Function_Mapper_Access is
begin
return Context.Function_Mapper;
end Get_Function_Mapper;
-- ------------------------------
-- Set the function mapper to be used when parsing an expression.
-- ------------------------------
overriding
procedure Set_Function_Mapper (Context : in out Default_Context;
Mapper : access EL.Functions.Function_Mapper'Class) is
begin
if Mapper = null then
Context.Function_Mapper := null;
else
Context.Function_Mapper := Mapper.all'Unchecked_Access;
end if;
end Set_Function_Mapper;
-- ------------------------------
-- Set the VariableMapper associated with this ELContext.
-- ------------------------------
overriding
procedure Set_Variable_Mapper (Context : in out Default_Context;
Mapper : access EL.Variables.VariableMapper'Class) is
use EL.Variables;
begin
if Mapper = null then
Context.Var_Mapper := null;
else
Context.Var_Mapper := Mapper.all'Unchecked_Access;
end if;
end Set_Variable_Mapper;
procedure Set_Variable (Context : in out Default_Context;
Name : in String;
Value : access EL.Beans.Readonly_Bean'Class) is
use EL.Variables;
begin
if Context.Var_Mapper = null then
Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper;
end if;
Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value));
end Set_Variable;
-- ------------------------------
-- Get the value associated with a base object and a given property.
-- ------------------------------
overriding
function Get_Value (Resolver : Default_ELResolver;
Context : ELContext'Class;
Base : access EL.Beans.Readonly_Bean'Class;
Name : Unbounded_String) return Object is
pragma Unreferenced (Context);
R : Object;
begin
if Base /= null then
return Base.Get_Value (To_String (Name));
end if;
declare
Pos : constant Bean_Maps.Cursor := Resolver.Map.Find (Name);
begin
if Bean_Maps.Has_Element (Pos) then
return Bean_Maps.Element (Pos);
end if;
end;
return R;
end Get_Value;
-- ------------------------------
-- Set the value associated with a base object and a given property.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in Default_ELResolver;
Context : in ELContext'Class;
Base : access EL.Beans.Bean'Class;
Name : in Unbounded_String;
Value : in Object) is
begin
null;
end Set_Value;
-- ------------------------------
-- Register the value under the given name.
-- ------------------------------
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : access EL.Beans.Readonly_Bean'Class) is
begin
Resolver.Register (Name, To_Object (Value));
end Register;
-- ------------------------------
-- Register the value under the given name.
-- ------------------------------
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : in EL.Objects.Object) is
begin
Bean_Maps.Include (Resolver.Map, Name, Value);
end Register;
end EL.Contexts.Default;
|
-----------------------------------------------------------------------
-- EL.Contexts -- Default contexts for evaluating an expression
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Variables.Default;
package body EL.Contexts.Default is
-- ------------------------------
-- Retrieves the ELResolver associated with this ELcontext.
-- ------------------------------
overriding
function Get_Resolver (Context : Default_Context) return ELResolver_Access is
begin
return Context.Resolver;
end Get_Resolver;
-- ------------------------------
-- Set the ELResolver associated with this ELcontext.
-- ------------------------------
procedure Set_Resolver (Context : in out Default_Context;
Resolver : in ELResolver_Access) is
begin
Context.Resolver := Resolver;
end Set_Resolver;
-- ------------------------------
-- Retrieves the VariableMapper associated with this ELContext.
-- ------------------------------
overriding
function Get_Variable_Mapper (Context : Default_Context)
return access EL.Variables.VariableMapper'Class is
begin
return Context.Var_Mapper;
end Get_Variable_Mapper;
-- ------------------------------
-- Retrieves the FunctionMapper associated with this ELContext.
-- The FunctionMapper is only used when parsing an expression.
-- ------------------------------
overriding
function Get_Function_Mapper (Context : Default_Context)
return EL.Functions.Function_Mapper_Access is
begin
return Context.Function_Mapper;
end Get_Function_Mapper;
-- ------------------------------
-- Set the function mapper to be used when parsing an expression.
-- ------------------------------
overriding
procedure Set_Function_Mapper (Context : in out Default_Context;
Mapper : access EL.Functions.Function_Mapper'Class) is
begin
if Mapper = null then
Context.Function_Mapper := null;
else
Context.Function_Mapper := Mapper.all'Unchecked_Access;
end if;
end Set_Function_Mapper;
-- ------------------------------
-- Set the VariableMapper associated with this ELContext.
-- ------------------------------
overriding
procedure Set_Variable_Mapper (Context : in out Default_Context;
Mapper : access EL.Variables.VariableMapper'Class) is
use EL.Variables;
begin
if Mapper = null then
Context.Var_Mapper := null;
else
Context.Var_Mapper := Mapper.all'Unchecked_Access;
end if;
end Set_Variable_Mapper;
procedure Set_Variable (Context : in out Default_Context;
Name : in String;
Value : access EL.Beans.Readonly_Bean'Class) is
use EL.Variables;
begin
if Context.Var_Mapper = null then
Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper;
end if;
Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value));
end Set_Variable;
-- ------------------------------
-- Get the value associated with a base object and a given property.
-- ------------------------------
overriding
function Get_Value (Resolver : Default_ELResolver;
Context : ELContext'Class;
Base : access EL.Beans.Readonly_Bean'Class;
Name : Unbounded_String) return Object is
pragma Unreferenced (Context);
R : Object;
begin
if Base /= null then
return Base.Get_Value (To_String (Name));
end if;
declare
Pos : constant Bean_Maps.Cursor := Resolver.Map.Find (Name);
begin
if Bean_Maps.Has_Element (Pos) then
return Bean_Maps.Element (Pos);
end if;
end;
return R;
end Get_Value;
-- ------------------------------
-- Set the value associated with a base object and a given property.
-- ------------------------------
overriding
procedure Set_Value (Resolver : in Default_ELResolver;
Context : in ELContext'Class;
Base : access EL.Beans.Bean'Class;
Name : in Unbounded_String;
Value : in Object) is
begin
null;
end Set_Value;
-- ------------------------------
-- Register the value under the given name.
-- ------------------------------
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : access EL.Beans.Readonly_Bean'Class) is
begin
Resolver.Register (Name, To_Object (Value));
end Register;
-- ------------------------------
-- Register the value under the given name.
-- ------------------------------
procedure Register (Resolver : in out Default_ELResolver;
Name : in Unbounded_String;
Value : in EL.Objects.Object) is
begin
Bean_Maps.Include (Resolver.Map, Name, Value);
end Register;
end EL.Contexts.Default;
|
Remove unused with clause
|
Remove unused with clause
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
ad0edbc5181f7d14b10a12acc2db62e162d2a22b
|
testcases/traits/traits.adb
|
testcases/traits/traits.adb
|
with Ada.Text_IO;
with AdaBase;
with Connect;
procedure Traits is
package TIO renames Ada.Text_IO;
package CON renames Connect;
-- Database_Driver renames specific driver using subtype
procedure display_versions (driver : CON.Database_Driver);
procedure display_traits (driver : CON.Database_Driver);
procedure display_versions (driver : CON.Database_Driver) is
begin
TIO.Put_Line (" client info: " & driver.trait_client_info);
TIO.Put_Line ("client version: " & driver.trait_client_version);
TIO.Put_Line (" server info: " & driver.trait_server_info);
TIO.Put_Line ("server version: " & driver.trait_server_version);
TIO.Put_Line (" driver: " & driver.trait_driver);
end display_versions;
procedure display_traits (driver : CON.Database_Driver) is
begin
TIO.Put_Line ("");
TIO.Put_Line (" autocommit: " & driver.trait_autocommit'Img);
TIO.Put_Line (" column case: " & driver.trait_column_case'Img);
TIO.Put_Line (" error_mode: " & driver.trait_error_mode'Img);
TIO.Put_Line (" blob_size: " & driver.trait_max_blob_size'Img);
end display_traits;
begin
CON.connect_database;
display_versions (driver => CON.DR);
display_traits (driver => CON.DR);
CON.DR.set_trait_autocommit (trait => True);
CON.DR.set_trait_column_case (trait => AdaBase.upper_case);
CON.DR.set_trait_error_mode (trait => AdaBase.silent);
CON.DR.set_trait_max_blob_size (trait => 2 ** 16);
display_traits (driver => CON.DR);
CON.DR.disconnect;
end Traits;
|
with Ada.Text_IO;
with Ada.Exceptions;
with AdaBase;
with Connect;
with GNAT.Traceback.Symbolic;
procedure Traits is
package SYM renames GNAT.Traceback.Symbolic;
package TIO renames Ada.Text_IO;
package CON renames Connect;
package EX renames Ada.Exceptions;
-- Database_Driver renames specific driver using subtype
procedure display_versions (driver : CON.Database_Driver);
procedure display_traits (driver : CON.Database_Driver);
procedure display_versions (driver : CON.Database_Driver) is
begin
TIO.Put_Line (" client info: " & driver.trait_client_info);
TIO.Put_Line ("client version: " & driver.trait_client_version);
TIO.Put_Line (" server info: " & driver.trait_server_info);
TIO.Put_Line ("server version: " & driver.trait_server_version);
TIO.Put_Line (" driver: " & driver.trait_driver);
end display_versions;
procedure display_traits (driver : CON.Database_Driver) is
begin
TIO.Put_Line ("");
TIO.Put_Line (" autocommit: " & driver.trait_autocommit'Img);
TIO.Put_Line (" column case: " & driver.trait_column_case'Img);
TIO.Put_Line (" error_mode: " & driver.trait_error_mode'Img);
TIO.Put_Line (" blob_size: " & driver.trait_max_blob_size'Img);
end display_traits;
begin
CON.connect_database;
display_versions (driver => CON.DR);
display_traits (driver => CON.DR);
CON.DR.set_trait_autocommit (trait => True);
CON.DR.set_trait_column_case (trait => AdaBase.upper_case);
CON.DR.set_trait_error_mode (trait => AdaBase.silent);
CON.DR.set_trait_max_blob_size (trait => 2 ** 16);
display_traits (driver => CON.DR);
CON.DR.disconnect;
exception
when E : others =>
TIO.Put_Line ("");
TIO.Put_Line ("exception name: " & EX.Exception_Name (E));
TIO.Put_Line ("exception msg : " & EX.Exception_Message (E));
TIO.Put_Line ("Traceback:");
TIO.Put_Line (SYM.Symbolic_Traceback (E));
end Traits;
|
Augment traits testcase with traceback functionality
|
Augment traits testcase with traceback functionality
PostgreSQL has been problematic and the symbolic traceback
helped a lot, so let's keep it. It doesn't affect the testcase
program itself as long as there is no error.
|
Ada
|
isc
|
jrmarino/AdaBase
|
93b83a77a7aa88a6e231a9bd6eb7cd8226cf259f
|
regtests/util-encoders-tests.ads
|
regtests/util-encoders-tests.ads
|
-----------------------------------------------------------------------
-- util-encodes-tests - Test for encoding
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Encoders.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Hex (T : in out Test);
procedure Test_Base64_Encode (T : in out Test);
procedure Test_Base64_Decode (T : in out Test);
procedure Test_Base64_URL_Encode (T : in out Test);
procedure Test_Base64_URL_Decode (T : in out Test);
procedure Test_Encoder (T : in out Test;
C : in out Util.Encoders.Encoder);
procedure Test_Base64_Benchmark (T : in out Test);
procedure Test_SHA1_Encode (T : in out Test);
-- Benchmark test for SHA1
procedure Test_SHA1_Benchmark (T : in out Test);
-- Test HMAC-SHA1
procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test);
-- Test encoding leb128.
procedure Test_LEB128 (T : in out Test);
end Util.Encoders.Tests;
|
-----------------------------------------------------------------------
-- util-encodes-tests - Test for encoding
-- Copyright (C) 2009, 2010, 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.Tests;
package Util.Encoders.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Hex (T : in out Test);
procedure Test_Base64_Encode (T : in out Test);
procedure Test_Base64_Decode (T : in out Test);
procedure Test_Base64_URL_Encode (T : in out Test);
procedure Test_Base64_URL_Decode (T : in out Test);
procedure Test_Encoder (T : in out Test;
C : in out Util.Encoders.Encoder);
procedure Test_Base64_Benchmark (T : in out Test);
procedure Test_SHA1_Encode (T : in out Test);
-- Benchmark test for SHA1
procedure Test_SHA1_Benchmark (T : in out Test);
-- Test HMAC-SHA1
procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test);
procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test);
-- Test encoding leb128.
procedure Test_LEB128 (T : in out Test);
-- Test encoding leb128 + base64url.
procedure Test_Base64_LEB128 (T : in out Test);
end Util.Encoders.Tests;
|
Declare Test_Base64_LEB128 procedure
|
Declare Test_Base64_LEB128 procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8f70c5610f460f9fbe22cbeeaa5b9880a91bb339
|
regtests/ado-tests.adb
|
regtests/ado-tests.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Calendar;
with ADO.Statements;
with ADO.Objects;
with ADO.Databases;
with ADO.Sessions;
with ADO.Utils;
with Regtests;
with Regtests.Simple.Model;
with Regtests.Images.Model;
with Util.Assertions;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Test_Caller;
package body ADO.Tests is
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests");
package Caller is new Util.Test_Caller (Test, "ADO");
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
T.Fail ("Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
T.Fail ("Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
use type ADO.Databases.Connection_Status;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Conn : constant ADO.Databases.Connection'Class := DB.Get_Connection;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
T.Assert (Conn.Get_Status = ADO.Databases.OPEN,
"The database connection is open");
T.Assert (DB.Get_Status = ADO.Databases.OPEN,
"The database connection is open");
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
-- ------------------------------
-- Test string insert.
-- ------------------------------
procedure Test_String (T : in out Test) is
use ADO.Objects;
use Ada.Strings.Unbounded;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
User : Regtests.Simple.Model.User_Ref;
Usr2 : Regtests.Simple.Model.User_Ref;
Name : Unbounded_String;
begin
for I in 1 .. 127 loop
Append (Name, Character'Val (I));
end loop;
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
DB.Begin_Transaction;
User.Set_Name (Name);
User.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Usr2.Load (DB, User.Get_Id);
Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name),
"Invalid name inserted for user");
end Test_String;
-- ------------------------------
-- Test blob insert.
-- ------------------------------
procedure Test_Blob (T : in out Test) is
use ADO.Objects;
use Ada.Streams;
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element);
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Img : Regtests.Images.Model.Image_Ref;
Size : constant Natural := 100;
Data : ADO.Blob_Ref := ADO.Create_Blob (Size);
Img2 : Regtests.Images.Model.Image_Ref;
begin
for I in 1 .. Size loop
Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255);
end loop;
DB.Begin_Transaction;
Img.Set_Image (Data);
Img.Set_Create_Date (Ada.Calendar.Clock);
Img.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
-- And verify that the blob data matches what we inserted.
Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len),
"Invalid blob length");
for I in 1 .. Data.Value.Len loop
Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I),
"Invalid blob content at " & Stream_Element_Offset'Image (I));
end loop;
-- Create a blob initialized with a file content.
Data := ADO.Create_Blob ("Makefile");
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob");
T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small");
declare
Content : Ada.Streams.Stream_Element_Array (1 .. 10);
Img3 : Regtests.Images.Model.Image_Ref;
begin
for I in Content'Range loop
Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30);
end loop;
Data := ADO.Create_Blob (Content);
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)");
T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small");
DB.Begin_Transaction;
Img3.Set_Image (Data);
Img3.Set_Create_Date (Ada.Calendar.Clock);
Img3.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img3.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
Img2.Set_Image (ADO.Null_Blob);
Img2.Save (DB);
DB.Commit;
end;
end Test_Blob;
-- ------------------------------
-- Test the To_Object and To_Identifier operations.
-- ------------------------------
procedure Test_Identifier_To_Object (T : in out Test) is
Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER);
begin
T.Assert (Util.Beans.Objects.Is_Null (Val),
"To_Object must return null for ADO.NO_IDENTIFIER");
T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER,
"To_Identifier must return ADO.NO_IDENTIFIER for null");
Val := ADO.Utils.To_Object (1);
T.Assert (not Util.Beans.Objects.Is_Null (Val),
"To_Object must not return null for a valid Identifier");
T.Assert (ADO.Utils.To_Identifier (Val) = 1,
"To_Identifier must return the correct identifier");
end Test_Identifier_To_Object;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access);
Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access);
Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access);
Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access);
Caller.Add_Test (Suite, "Test insert string",
Test_String'Access);
Caller.Add_Test (Suite, "Test insert blob",
Test_Blob'Access);
Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier",
Test_Identifier_To_Object'Access);
end Add_Tests;
end ADO.Tests;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Calendar;
with ADO.Statements;
with ADO.Objects;
with ADO.Databases;
with ADO.Sessions;
with ADO.Utils;
with Regtests;
with Regtests.Simple.Model;
with Regtests.Images.Model;
with Util.Assertions;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Test_Caller;
package body ADO.Tests is
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests");
package Caller is new Util.Test_Caller (Test, "ADO");
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
T.Fail ("Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
T.Fail ("Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
use type ADO.Sessions.Connection_Status;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
T.Assert (DB.Get_Status = ADO.Sessions.OPEN,
"The database connection is open");
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
-- ------------------------------
-- Test string insert.
-- ------------------------------
procedure Test_String (T : in out Test) is
use ADO.Objects;
use Ada.Strings.Unbounded;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
User : Regtests.Simple.Model.User_Ref;
Usr2 : Regtests.Simple.Model.User_Ref;
Name : Unbounded_String;
begin
for I in 1 .. 127 loop
Append (Name, Character'Val (I));
end loop;
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
DB.Begin_Transaction;
User.Set_Name (Name);
User.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Usr2.Load (DB, User.Get_Id);
Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name),
"Invalid name inserted for user");
end Test_String;
-- ------------------------------
-- Test blob insert.
-- ------------------------------
procedure Test_Blob (T : in out Test) is
use ADO.Objects;
use Ada.Streams;
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element);
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Img : Regtests.Images.Model.Image_Ref;
Size : constant Natural := 100;
Data : ADO.Blob_Ref := ADO.Create_Blob (Size);
Img2 : Regtests.Images.Model.Image_Ref;
begin
for I in 1 .. Size loop
Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255);
end loop;
DB.Begin_Transaction;
Img.Set_Image (Data);
Img.Set_Create_Date (Ada.Calendar.Clock);
Img.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
-- And verify that the blob data matches what we inserted.
Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len),
"Invalid blob length");
for I in 1 .. Data.Value.Len loop
Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I),
"Invalid blob content at " & Stream_Element_Offset'Image (I));
end loop;
-- Create a blob initialized with a file content.
Data := ADO.Create_Blob ("Makefile");
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob");
T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small");
declare
Content : Ada.Streams.Stream_Element_Array (1 .. 10);
Img3 : Regtests.Images.Model.Image_Ref;
begin
for I in Content'Range loop
Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30);
end loop;
Data := ADO.Create_Blob (Content);
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)");
T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small");
DB.Begin_Transaction;
Img3.Set_Image (Data);
Img3.Set_Create_Date (Ada.Calendar.Clock);
Img3.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img3.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
Img2.Set_Image (ADO.Null_Blob);
Img2.Save (DB);
DB.Commit;
end;
end Test_Blob;
-- ------------------------------
-- Test the To_Object and To_Identifier operations.
-- ------------------------------
procedure Test_Identifier_To_Object (T : in out Test) is
Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER);
begin
T.Assert (Util.Beans.Objects.Is_Null (Val),
"To_Object must return null for ADO.NO_IDENTIFIER");
T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER,
"To_Identifier must return ADO.NO_IDENTIFIER for null");
Val := ADO.Utils.To_Object (1);
T.Assert (not Util.Beans.Objects.Is_Null (Val),
"To_Object must not return null for a valid Identifier");
T.Assert (ADO.Utils.To_Identifier (Val) = 1,
"To_Identifier must return the correct identifier");
end Test_Identifier_To_Object;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access);
Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access);
Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access);
Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access);
Caller.Add_Test (Suite, "Test insert string",
Test_String'Access);
Caller.Add_Test (Suite, "Test insert blob",
Test_Blob'Access);
Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier",
Test_Identifier_To_Object'Access);
end Add_Tests;
end ADO.Tests;
|
Update the unit test after refactorisation of ADO.Sessions
|
Update the unit test after refactorisation of ADO.Sessions
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
c0bf67585a586dbb40412b807cc67ca4e1a6930a
|
src/security-permissions.adb
|
src/security-permissions.adb
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.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
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := 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;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := Permission_Index'First;
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;
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);
Next_Index := Next_Index + 1;
end if;
end Add_Permission;
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 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;
package body Permission_ACL is
P : Permission_Index;
function Permission return Permission_Index is
begin
return P;
end Permission;
begin
Add_Permission (Name => Name, Index => P);
end Permission_ACL;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.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
use Util.Log;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The logger
Log : constant Loggers.Logger := 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;
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
Map : Permission_Maps.Map;
Next_Index : Permission_Index := Permission_Index'First;
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;
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);
Next_Index := Next_Index + 1;
end if;
end Add_Permission;
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 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;
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;
|
Rename Permission_ACL into Definition
|
Rename Permission_ACL into Definition
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
087cc07e3636cda2653827059126dac8ce69bf8c
|
awa/plugins/awa-questions/regtests/awa-questions-tests.adb
|
awa/plugins/awa-questions/regtests/awa-questions-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-tests -- Unit tests for questions module
-- 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.Strings;
with Servlet.Streams;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Questions");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load_List (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load (missing)",
Test_Missing_Page'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the wiki as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String) is
function Get_Link (Title : in String) return String;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
function Get_Link (Title : in String) return String is
Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title);
end Get_Link;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/list.html",
"question-list.html");
ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply,
"Questions list page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/questions/tags/tag",
"question-list-tagged.html");
ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply,
"Questions tag page is invalid");
if Page'Length > 0 then
ASF.Tests.Do_Get (Request, Reply, "/questions/view/" & Page,
"question-page-" & Page & ".html");
ASF.Tests.Assert_Contains (T, Title, Reply,
"Question page " & Page & " is invalid");
ASF.Tests.Assert_Contains (T, "<h2>" & Title & "</h2>", Reply,
"Question page " & Page & " is invalid");
ASF.Tests.Assert_Matches (T, ".input type=.hidden. name=.question-id. "
& "value=.[0-9]+. id=.question-id.../input", Reply,
"Question page " & Page & " is invalid");
end if;
end Verify_Anonymous;
-- ------------------------------
-- Verify that the question list contains the given question.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Id : in String;
Title : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/list.html",
"question-list-recent.html");
ASF.Tests.Assert_Contains (T, "Questions", Reply,
"List of questions page is invalid");
ASF.Tests.Assert_Contains (T, "/questions/view/" & Id, Reply,
"List of questions page does not reference the page");
ASF.Tests.Assert_Contains (T, Title, Reply,
"List of questions page does not contain the question");
end Verify_List_Contains;
-- ------------------------------
-- Test access to the question as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("", "");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of question by simulating web requests.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
procedure Create_Question (Title : in String);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
procedure Create_Question (Title : in String) is
begin
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("title", Title);
Request.Set_Parameter ("text", "# Main title" & ASCII.LF
& "* The question content." & ASCII.LF
& "* Second item." & ASCII.LF);
Request.Set_Parameter ("save", "1");
ASF.Tests.Do_Post (Request, Reply, "/questions/ask.html", "questions-ask.html");
T.Question_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/questions/view/");
Util.Tests.Assert_Matches (T, "[0-9]+$", To_String (T.Question_Ident),
"Invalid redirect after question creation");
-- Remove the 'question' bean from the request so that we get a new instance
-- for the next call.
Request.Remove_Attribute ("question");
end Create_Question;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Create_Question ("Question 1 page title1");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 1 page title1");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 1 page title1");
Create_Question ("Question 2 page title2");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 2 page title2");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 2 page title2");
Create_Question ("Question 3 page title3");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 3 page title3");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 3 page title3");
end Test_Create_Question;
-- ------------------------------
-- Test getting a wiki page which does not exist.
-- ------------------------------
procedure Test_Missing_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/view.html?id=12345678",
"question-page-missing.html");
ASF.Tests.Assert_Matches (T, "<title>Question not found</title>", Reply,
"Question page title '12345678' is invalid",
ASF.Responses.SC_NOT_FOUND);
ASF.Tests.Assert_Matches (T, "question.*removed", Reply,
"Question page content '12345678' is invalid",
ASF.Responses.SC_NOT_FOUND);
end Test_Missing_Page;
end AWA.Questions.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-tests -- Unit tests for questions module
-- 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.Strings;
with Servlet.Streams;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
package Caller is new Util.Test_Caller (Test, "Questions");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load_List (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load (missing)",
Test_Missing_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save (answer)",
Test_Answer_Question'Access);
end Add_Tests;
-- ------------------------------
-- Get some access on the wiki as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String) is
function Get_Link (Title : in String) return String;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
function Get_Link (Title : in String) return String is
Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title);
end Get_Link;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/list.html",
"question-list.html");
ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply,
"Questions list page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/questions/tags/tag",
"question-list-tagged.html");
ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply,
"Questions tag page is invalid");
if Page'Length > 0 then
ASF.Tests.Do_Get (Request, Reply, "/questions/view/" & Page,
"question-page-" & Page & ".html");
ASF.Tests.Assert_Contains (T, Title, Reply,
"Question page " & Page & " is invalid");
ASF.Tests.Assert_Matches (T, ".input type=.hidden. name=.question-id. "
& "value=.[0-9]+. id=.question-id.../input", Reply,
"Question page " & Page & " is invalid");
end if;
end Verify_Anonymous;
-- ------------------------------
-- Verify that the question list contains the given question.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Id : in String;
Title : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/list.html",
"question-list-recent.html");
ASF.Tests.Assert_Contains (T, "Questions", Reply,
"List of questions page is invalid");
ASF.Tests.Assert_Contains (T, "/questions/view/" & Id, Reply,
"List of questions page does not reference the page");
ASF.Tests.Assert_Contains (T, Title, Reply,
"List of questions page does not contain the question");
end Verify_List_Contains;
-- ------------------------------
-- Test access to the question as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("", "");
end Test_Anonymous_Access;
-- ------------------------------
-- Test creation of question by simulating web requests.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
procedure Create_Question (Title : in String);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Uuid : constant String := Util.Tests.Get_Uuid;
procedure Create_Question (Title : in String) is
begin
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("title", Title);
Request.Set_Parameter ("text", "# Main title" & ASCII.LF
& "* The question content." & ASCII.LF
& "* Second item." & ASCII.LF);
Request.Set_Parameter ("save", "1");
ASF.Tests.Do_Post (Request, Reply, "/questions/ask.html", "questions-ask.html");
T.Question_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/questions/view/");
Util.Tests.Assert_Matches (T, "[0-9]+$", To_String (T.Question_Ident),
"Invalid redirect after question creation");
-- Remove the 'question' bean from the request so that we get a new instance
-- for the next call.
Request.Remove_Attribute ("question");
end Create_Question;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Create_Question ("Question 1 page title1");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 1 page title1");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 1 page title1");
Create_Question ("Question 2 page title2");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 2 page title2");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 2 page title2");
Create_Question ("Question 3 page title3");
T.Verify_List_Contains (To_String (T.Question_Ident), "Question 3 page title3");
T.Verify_Anonymous (To_String (T.Question_Ident), "Question 3 page title3");
end Test_Create_Question;
-- ------------------------------
-- Test getting a wiki page which does not exist.
-- ------------------------------
procedure Test_Missing_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/questions/view.html?id=12345678",
"question-page-missing.html");
ASF.Tests.Assert_Matches (T, "<title>Question not found</title>", Reply,
"Question page title '12345678' is invalid",
ASF.Responses.SC_NOT_FOUND);
ASF.Tests.Assert_Matches (T, "question.*removed", Reply,
"Question page content '12345678' is invalid",
ASF.Responses.SC_NOT_FOUND);
end Test_Missing_Page;
-- ------------------------------
-- Test answer of question by simulating web requests.
-- ------------------------------
procedure Test_Answer_Question (T : in out Test) is
procedure Create_Answer (Content : in String);
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
procedure Create_Answer (Content : in String) is
begin
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("question-id", To_String (T.Question_Ident));
Request.Set_Parameter ("answer-id", "");
Request.Set_Parameter ("text", Content);
Request.Set_Parameter ("save", "1");
ASF.Tests.Do_Post (Request, Reply, "/questions/forms/answer-form.html",
"questions-answer.html");
ASF.Tests.Assert_Contains (T, "/questions/view/" & To_String (T.Question_Ident),
Reply,
"Answer response is invalid");
-- Remove the 'question' bean from the request so that we get a new instance
-- for the next call.
Request.Remove_Attribute ("answer");
end Create_Answer;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Create_Answer ("Answer content 1");
T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1");
Create_Answer ("Answer content 2");
T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1");
T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2");
Create_Answer ("Answer content 3");
T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1");
T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2");
T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 3");
end Test_Answer_Question;
end AWA.Questions.Tests;
|
Implement Test_Answer_Question to check answering a question
|
Implement Test_Answer_Question to check answering a question
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
9d154f96193315522c4387d0ce5bbc329706d3e3
|
src/util-properties-json.adb
|
src/util-properties-json.adb
|
-----------------------------------------------------------------------
-- util-properties-json -- read json files into properties
-- Copyright (C) 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
with Util.Stacks;
with Util.Beans.Objects;
package body Util.Properties.JSON is
type Natural_Access is access all Natural;
package Length_Stack is new Util.Stacks (Element_Type => Natural,
Element_Type_Access => Natural_Access);
type Parser is new Util.Serialize.IO.JSON.Parser with record
Base_Name : Ada.Strings.Unbounded.Unbounded_String;
Lengths : Length_Stack.Stack;
Separator : Ada.Strings.Unbounded.Unbounded_String;
Separator_Length : Natural;
end record;
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String);
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String);
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural);
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String) is
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Append (Handler.Base_Name, Name);
Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator);
Length_Stack.Push (Handler.Lengths);
Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length;
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name);
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Delete (Handler.Base_Name,
Len - Name'Length - Handler.Separator_Length + 1, Len);
end if;
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String) is
begin
Handler.Start_Object (Name);
Util.Serialize.IO.JSON.Parser (Handler).Start_Array (Name);
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural) is
begin
Parser'Class (Handler).Set_Member ("length", Util.Beans.Objects.To_Object (Count));
Handler.Finish_Object (Name);
Util.Serialize.IO.JSON.Parser (Handler).Finish_Array (Name, Count);
end Finish_Array;
-- -----------------------
-- Parse the JSON content and put the flattened content in the property manager.
-- -----------------------
procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class;
Content : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with record
Manager : access Util.Properties.Manager'Class;
end record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Manager := Manager'Access;
P.Parse_String (Content);
if P.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Parse_JSON;
-- -----------------------
-- Read the JSON file into the property manager.
-- The JSON content is flatten into Flatten the JSON content and add the properties.
-- -----------------------
procedure Read_JSON (Manager : in out Util.Properties.Manager'Class;
Path : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with record
Manager : access Util.Properties.Manager'Class;
end record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
begin
P.Manager := Manager'Access;
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Parse (Path);
if P.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Read_JSON;
end Util.Properties.JSON;
|
-----------------------------------------------------------------------
-- util-properties-json -- read json files into properties
-- Copyright (C) 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
with Util.Stacks;
with Util.Beans.Objects;
package body Util.Properties.JSON is
type Natural_Access is access all Natural;
package Length_Stack is new Util.Stacks (Element_Type => Natural,
Element_Type_Access => Natural_Access);
type Parser is abstract limited new Util.Serialize.IO.Reader with record
Base_Name : Ada.Strings.Unbounded.Unbounded_String;
Lengths : Length_Stack.Stack;
Separator : Ada.Strings.Unbounded.Unbounded_String;
Separator_Length : Natural;
end record;
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String);
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String);
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural);
-- 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);
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Parser;
Name : in String) is
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Append (Handler.Base_Name, Name);
Ada.Strings.Unbounded.Append (Handler.Base_Name, Handler.Separator);
Length_Stack.Push (Handler.Lengths);
Length_Stack.Current (Handler.Lengths).all := Name'Length + Handler.Separator_Length;
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
Len : constant Natural := Ada.Strings.Unbounded.Length (Handler.Base_Name);
begin
if Name'Length > 0 then
Ada.Strings.Unbounded.Delete (Handler.Base_Name,
Len - Name'Length - Handler.Separator_Length + 1, Len);
end if;
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Parser;
Name : in String) is
begin
Handler.Start_Object (Name);
-- Util.Serialize.IO.JSON.Parser (Handler).Start_Array (Name);
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural) is
begin
Parser'Class (Handler).Set_Member ("length", Util.Beans.Objects.To_Object (Count));
Handler.Finish_Object (Name);
-- Util.Serialize.IO.JSON.Parser (Handler).Finish_Array (Name, Count);
end Finish_Array;
-- 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) is
begin
null;
end Error;
-- -----------------------
-- Parse the JSON content and put the flattened content in the property manager.
-- -----------------------
procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class;
Content : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with record
Manager : access Util.Properties.Manager'Class;
end record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
R : Util.Serialize.IO.JSON.Parser;
begin
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
P.Manager := Manager'Access;
R.Parse_String (Content, P);
if R.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Parse_JSON;
-- -----------------------
-- Read the JSON file into the property manager.
-- The JSON content is flatten into Flatten the JSON content and add the properties.
-- -----------------------
procedure Read_JSON (Manager : in out Util.Properties.Manager'Class;
Path : in String;
Flatten_Separator : in String := ".") is
type Local_Parser is new Parser with record
Manager : access Util.Properties.Manager'Class;
end record;
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False);
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Local_Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
pragma Unreferenced (Attribute);
begin
Handler.Manager.Set (Ada.Strings.Unbounded.To_String (Handler.Base_Name) & Name,
Util.Beans.Objects.To_String (Value));
end Set_Member;
P : Local_Parser;
R : Util.Serialize.IO.JSON.Parser;
begin
P.Manager := Manager'Access;
P.Separator := Ada.Strings.Unbounded.To_Unbounded_String (Flatten_Separator);
P.Separator_Length := Flatten_Separator'Length;
R.Parse (Path, P);
if R.Has_Error then
raise Util.Serialize.IO.Parse_Error;
end if;
end Read_JSON;
end Util.Properties.JSON;
|
Update the JSON properties parser to the new parser/mapper interfaces
|
Update the JSON properties parser to the new parser/mapper interfaces
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e6c3e4a3d12c1a9e512bf0efad58a825a2f08058
|
src/babel-files.ads
|
src/babel-files.ads
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Encoders.SHA1;
with ADO;
package Babel.Files is
NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER;
subtype File_Identifier is ADO.Identifier;
subtype Directory_Identifier is ADO.Identifier;
subtype File_Size is Long_Long_Integer;
type File_Mode is mod 2**16;
type Uid_Type is mod 2**16;
type Gid_Type is mod 2**16;
type File_Type is private;
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
type Directory_Type is private;
type Directory_Type_Array is array (Positive range <>) of Directory_Type;
type Directory_Type_Array_Access is access all Directory_Type_Array;
NO_DIRECTORY : constant Directory_Type;
NO_FILE : constant File_Type;
type Status_Type is mod 2**16;
-- The file was modified.
FILE_MODIFIED : constant Status_Type := 16#0001#;
-- There was some error while processing this file.
FILE_ERROR : constant Status_Type := 16#8000#;
-- The SHA1 signature for the file is known and valid.
FILE_HAS_SHA1 : constant Status_Type := 16#0002#;
-- Allocate a File_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type;
-- Allocate a Directory_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type;
type File (Len : Positive) is record
Id : File_Identifier := NO_IDENTIFIER;
Size : File_Size := 0;
Dir : Directory_Type := NO_DIRECTORY;
Mode : File_Mode := 8#644#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Status : Status_Type := 0;
Date : Ada.Calendar.Time;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Name : aliased String (1 .. Len);
end record;
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File_Type) return Boolean;
-- Set the file as modified.
procedure Set_Modified (Element : in File_Type);
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array);
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
procedure Set_Size (Element : in File_Type;
Size : in File_Size);
-- Return the path for the file.
function Get_Path (Element : in File_Type) return String;
-- Return the path for the directory.
function Get_Path (Element : in Directory_Type) return String;
-- Return the SHA1 signature computed for the file.
function Get_SHA1 (Element : in File_Type) return String;
type File_Container is limited interface;
-- Add the file with the given name in the container.
procedure Add_File (Into : in out File_Container;
Element : in File_Type) is abstract;
-- Add the directory with the given name in the container.
procedure Add_Directory (Into : in out File_Container;
Element : in Directory_Type) is abstract;
-- Create a new file instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return File_Type is abstract;
-- Create a new directory instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
function Find (From : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
function Find (From : in File_Container;
Name : in String) return Directory_Type is abstract;
type Default_Container is new File_Container with private;
-- Add the file with the given name in the container.
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type);
-- Add the directory with the given name in the container.
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type);
-- Create a new file instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type;
-- Create a new directory instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type;
private
type Directory (Len : Positive) is record
Id : Directory_Identifier := NO_IDENTIFIER;
Parent : Directory_Type;
Mode : File_Mode := 8#755#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Files : File_Type_Array_Access;
Children : Directory_Type_Array_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : aliased String (1 .. Len);
end record;
type File_Type is access all File;
type Directory_Type is access all Directory;
type Default_Container is new Babel.Files.File_Container with record
Current : Directory_Type;
end record;
NO_DIRECTORY : constant Directory_Type := null;
NO_FILE : constant File_Type := null;
end Babel.Files;
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Util.Encoders.SHA1;
with ADO;
package Babel.Files is
NO_IDENTIFIER : constant ADO.Identifier := ADO.NO_IDENTIFIER;
subtype File_Identifier is ADO.Identifier;
subtype Directory_Identifier is ADO.Identifier;
subtype File_Size is Long_Long_Integer;
type File_Mode is mod 2**16;
type Uid_Type is mod 2**16;
type Gid_Type is mod 2**16;
type File_Type is private;
type File_Type_Array is array (Positive range <>) of File_Type;
type File_Type_Array_Access is access all File_Type_Array;
type Directory_Type is private;
type Directory_Type_Array is array (Positive range <>) of Directory_Type;
type Directory_Type_Array_Access is access all Directory_Type_Array;
NO_DIRECTORY : constant Directory_Type;
NO_FILE : constant File_Type;
type Status_Type is mod 2**16;
-- The file was modified.
FILE_MODIFIED : constant Status_Type := 16#0001#;
-- There was some error while processing this file.
FILE_ERROR : constant Status_Type := 16#8000#;
-- The SHA1 signature for the file is known and valid.
FILE_HAS_SHA1 : constant Status_Type := 16#0002#;
-- Allocate a File_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type;
-- Allocate a Directory_Type entry with the given name for the directory.
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type;
type File (Len : Positive) is record
Id : File_Identifier := NO_IDENTIFIER;
Size : File_Size := 0;
Dir : Directory_Type := NO_DIRECTORY;
Mode : File_Mode := 8#644#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Status : Status_Type := 0;
Date : Ada.Calendar.Time;
SHA1 : Util.Encoders.SHA1.Hash_Array;
Name : aliased String (1 .. Len);
end record;
-- Return true if the file was modified and need a backup.
function Is_Modified (Element : in File_Type) return Boolean;
-- Set the file as modified.
procedure Set_Modified (Element : in File_Type);
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array);
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
procedure Set_Size (Element : in File_Type;
Size : in File_Size);
-- Return the path for the file.
function Get_Path (Element : in File_Type) return String;
-- Return the path for the directory.
function Get_Path (Element : in Directory_Type) return String;
-- Return the SHA1 signature computed for the file.
function Get_SHA1 (Element : in File_Type) return String;
type File_Container is limited interface;
-- Add the file with the given name in the container.
procedure Add_File (Into : in out File_Container;
Element : in File_Type) is abstract;
-- Add the directory with the given name in the container.
procedure Add_Directory (Into : in out File_Container;
Element : in Directory_Type) is abstract;
-- Create a new file instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return File_Type is abstract;
-- Create a new directory instance with the given name in the container.
function Create (Into : in File_Container;
Name : in String) return Directory_Type is abstract;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
function Find (From : in File_Container;
Name : in String) return File_Type is abstract;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
function Find (From : in File_Container;
Name : in String) return Directory_Type is abstract;
type Default_Container is new File_Container with private;
-- Add the file with the given name in the container.
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type);
-- Add the directory with the given name in the container.
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type);
-- Create a new file instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type;
-- Create a new directory instance with the given name in the container.
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type;
private
type File_Type is access all File;
type Directory (Len : Positive) is record
Id : Directory_Identifier := NO_IDENTIFIER;
Parent : Directory_Type;
Mode : File_Mode := 8#755#;
User : Uid_Type := 0;
Group : Gid_Type := 0;
Files : File_Type_Array_Access;
Children : Directory_Type_Array_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Name : aliased String (1 .. Len);
end record;
type Directory_Type is access all Directory;
package File_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => File_Type,
"=" => "=");
package Directory_Vectors is new
Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_Type,
"=" => "=");
type Default_Container is new Babel.Files.File_Container with record
Current : Directory_Type;
Files : File_Vectors.Vector;
Dirs : Directory_Vectors.Vector;
end record;
NO_DIRECTORY : constant Directory_Type := null;
NO_FILE : constant File_Type := null;
end Babel.Files;
|
Define the File_Vectors and Directory_Vectors packages
|
Define the File_Vectors and Directory_Vectors packages
|
Ada
|
apache-2.0
|
stcarrez/babel
|
2d00885c673a1752508d36230e24a1c731b777dd
|
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 := "02";
copyright_years : constant String := "2015-2018";
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 := "gcc7";
compiler_version : constant String := "7.3.0";
previous_compiler : constant String := "7.2.0";
binutils_version : constant String := "2.30";
previous_binutils : constant String := "2.29.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 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type 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";
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 := "03";
copyright_years : constant String := "2015-2018";
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 := "gcc7";
compiler_version : constant String := "7.3.0";
previous_compiler : constant String := "7.2.0";
binutils_version : constant String := "2.30";
previous_binutils : constant String := "2.29.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 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type 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";
host_pkg8 : constant String := host_localbase & "/sbin/pkg-static";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Bump version to 1.03
|
Bump version to 1.03
This fixes GITHUB_PRIVATE regression.
Requires related fixes in sites.sh and raven.sequence.mk
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
a04c595927c8893394009845eedf0905cc64603f
|
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);
-- Test Create_Role and Get_Role_Name
procedure Test_Create_Role (T : in out Test);
-- Test Has_Permission
procedure Test_Has_Permission (T : in out Test);
-- Test reading policy files
procedure Test_Read_Policy (T : in out Test);
-- Test reading policy files and using the <role-permission> controller
procedure Test_Role_Policy (T : in out Test);
-- 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);
type Test_Principal is new Principal with record
Name : Util.Strings.String_Ref;
Roles : Role_Map := (others => False);
end record;
-- 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;
-- Get the principal name.
function Get_Name (From : in Test_Principal) return String;
end Security.Permissions.Tests;
|
-----------------------------------------------------------------------
-- 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;
|
Remove the policy specific unit tests
|
Remove the policy specific unit tests
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
ab6b151a1d44cc2fdc01e7aa7a1a7e8ee7d35298
|
src/ado-utils-serialize.ads
|
src/ado-utils-serialize.ads
|
-----------------------------------------------------------------------
-- ado-utils-serialize -- Utility operations for JSON/XML serialization
-- 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 Util.Serialize.IO;
with ADO.Objects;
package ADO.Utils.Serialize is
-- Write the entity to the serialization stream (JSON/XML).
procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class;
Name : in String;
Value : in ADO.Identifier);
-- Write the entity to the serialization stream (JSON/XML).
procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class;
Name : in String;
Value : in ADO.Objects.Object_Key);
end ADO.Utils.Serialize;
|
-----------------------------------------------------------------------
-- ado-utils-serialize -- Utility operations for JSON/XML serialization
-- Copyright (C) 2016, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO;
with ADO.Objects;
with ADO.Statements;
package ADO.Utils.Serialize is
-- Write the entity to the serialization stream (JSON/XML).
procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class;
Name : in String;
Value : in ADO.Identifier);
-- Write the entity to the serialization stream (JSON/XML).
procedure Write_Entity (Stream : in out Util.Serialize.IO.Output_Stream'Class;
Name : in String;
Value : in ADO.Objects.Object_Key);
-- Write the SQL query results to the serialization stream (JSON/XML).
procedure Write_Query (Stream : in out Util.Serialize.IO.Output_Stream'Class;
Name : in String;
Query : in out ADO.Statements.Query_Statement);
end ADO.Utils.Serialize;
|
Declare Write_Query procedure to serialize the result of a Query_Statement
|
Declare Write_Query procedure to serialize the result of a Query_Statement
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
1ef8ce1d1cd50bf9fcb7f16251e5762a0e5c0c38
|
src/asf-views.ads
|
src/asf-views.ads
|
-----------------------------------------------------------------------
-- asf-views -- Views
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Views</b> package defines the abstractions to represent
-- an XHTML view that can be instantiated to create the JSF component
-- tree. The <b>ASF.Views</b> are read only once and they are shared
-- by the JSF component trees that are instantiated from it.
--
-- The XHTML view is read using a SAX parser which creates nodes
-- and attributes to represent the view.
--
-- The <b>ASF.Views</b> is composed of nodes represented by <b>Tag_Node</b>
-- and attributes represented by <b>Tag_Attribute</b>. In a sense, this
-- is very close to an XML DOM tree.
package ASF.Views is
-- ------------------------------
-- Source line information
-- ------------------------------
type File_Info (<>) is limited private;
type File_Info_Access is access all File_Info;
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access;
-- Get the relative path name
function Relative_Path (File : in File_Info) return String;
type Line_Info is private;
-- Get the line number
function Line (Info : in Line_Info) return Natural;
pragma Inline (Line);
-- Get the source file
function File (Info : in Line_Info) return String;
pragma Inline (File);
private
type File_Info (Length : Natural) is limited record
Relative_Pos : Natural;
Path : String (1 .. Length);
end record;
NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0);
type Line_Info is record
Line : Natural := 0;
Column : Natural := 0;
File : File_Info_Access := NO_FILE'Access;
end record;
end ASF.Views;
|
-----------------------------------------------------------------------
-- asf-views -- Views
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Views</b> package defines the abstractions to represent
-- an XHTML view that can be instantiated to create the JSF component
-- tree. The <b>ASF.Views</b> are read only once and they are shared
-- by the JSF component trees that are instantiated from it.
--
-- The XHTML view is read using a SAX parser which creates nodes
-- and attributes to represent the view.
--
-- The <b>ASF.Views</b> is composed of nodes represented by <b>Tag_Node</b>
-- and attributes represented by <b>Tag_Attribute</b>. In a sense, this
-- is very close to an XML DOM tree.
package ASF.Views is
pragma Preelaborate;
-- ------------------------------
-- Source line information
-- ------------------------------
type File_Info (<>) is limited private;
type File_Info_Access is access all File_Info;
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access;
-- Get the relative path name
function Relative_Path (File : in File_Info) return String;
type Line_Info is private;
-- Get the line number
function Line (Info : in Line_Info) return Natural;
pragma Inline (Line);
-- Get the source file
function File (Info : in Line_Info) return String;
pragma Inline (File);
private
type File_Info (Length : Natural) is limited record
Relative_Pos : Natural;
Path : String (1 .. Length);
end record;
NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0);
type Line_Info is record
Line : Natural := 0;
Column : Natural := 0;
File : File_Info_Access := NO_FILE'Access;
end record;
end ASF.Views;
|
Make the package Preelaborate
|
Make the package Preelaborate
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
ac299d6fd3bc1427150f977383540c0b1d795329
|
awa/plugins/awa-countries/tools/import_country.adb
|
awa/plugins/awa-countries/tools/import_country.adb
|
-----------------------------------------------------------------------
-- import_country -- Read a Country csv file to update the database
-- 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.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with ADO;
with ADO.SQL;
with ADO.Drivers;
with ADO.Sessions;
with ADO.Statements;
with ADO.Sessions.Factory;
with Util.Strings;
with Util.Log.Loggers;
with Util.Serialize.IO.CSV;
with AWA.Countries.Models;
procedure Import_Country is
use Ada.Text_IO;
use Util.Serialize.IO.CSV;
use AWA.Countries.Models;
use Ada.Containers;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Import_Country");
Country : AWA.Countries.Models.Country_Ref;
DB : ADO.Sessions.Master_Session;
package Country_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => AWA.Countries.Models.Country_Ref,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
package Neighbors_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
Countries : Country_Map.Map;
Neighbors : Neighbors_Map.Map;
type CSV_Parser is new Util.Serialize.IO.CSV.Parser with null record;
overriding
procedure Set_Cell (Parser : in out CSV_Parser;
Value : in String;
Row : in Util.Serialize.IO.CSV.Row_Type;
Column : in Util.Serialize.IO.CSV.Column_Type);
overriding
procedure Set_Cell (Parser : in out CSV_Parser;
Value : in String;
Row : in Util.Serialize.IO.CSV.Row_Type;
Column : in Util.Serialize.IO.CSV.Column_Type) is
pragma Unreferenced (Parser, Row);
Query : ADO.SQL.Query;
Found : Boolean;
begin
case Column is
when 1 =>
-- The ISO code is unique, find the country
Query.Bind_Param (1, Value);
Query.Set_Filter ("iso_code = ?");
Country.Find (DB, Query, Found);
if not Found then
-- Build a new country object
Country := AWA.Countries.Models.Null_Country;
Country.Set_Iso_Code (Value);
end if;
Countries.Insert (Value, Country);
when 2 =>
-- Ada.Text_IO.Put_Line ("ISO3: " & Value);
null;
when 3 =>
-- Ada.Text_IO.Put_Line ("ISON: " & Value);
null;
when 4 =>
-- Ada.Text_IO.Put_Line ("FIPS: " & Value);
null;
-- Country name
when 5 =>
Country.Set_Name (Value);
when 6 =>
-- Ada.Text_IO.Put_Line ("Capital: " & Value);
null;
when 7 | 8 => -- Area, Population
null;
-- Country continent
when 9 =>
Country.Set_Continent (Value);
-- Country TLD
when 10 =>
Country.Set_Tld (Value);
-- Country CurrencyCode
when 11 =>
Country.Set_Currency_Code (Value);
-- Country CurrencyName
when 12 =>
Country.Set_Currency (Value);
when 13 | 14 => -- Phone, postal code format
null;
when 15 =>
-- Ada.Text_IO.Put_Line ("Postal regex: " & Value);
null;
-- Country languages
when 16 =>
Country.Set_Languages (Value);
-- Country unique geonameid
when 17 =>
if Value /= "" then
Country.Set_Geonameid (Integer'Value (Value));
end if;
when 18 =>
Country.Save (DB);
Neighbors.Insert (Country.Get_Iso_Code, Value);
when 19 => -- EquivalentFipsCode
null;
when others =>
null;
end case;
exception
when E : others =>
Log.Error ("Column " & Util.Serialize.IO.CSV.Column_Type'Image (Column)
& " value: " & Value, E, True);
raise;
end Set_Cell;
procedure Build_Neighbors is
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Countries.Models.COUNTRY_NEIGHBOR_TABLE);
Iter : Neighbors_Map.Cursor := Neighbors.First;
Count : Natural := 0;
begin
Stmt.Execute;
while Neighbors_Map.Has_Element (Iter) loop
declare
Name : constant String := Neighbors_Map.Key (Iter);
List : constant String := Neighbors_Map.Element (Iter);
Pos : Natural := List'First;
N : Natural;
begin
Country := Countries.Element (Name);
while Pos < List'Last loop
N := Util.Strings.Index (List, ',', Pos);
if N = 0 then
N := List'Last;
else
N := N - 1;
end if;
if Pos < N and then Countries.Contains (List (Pos .. N)) then
declare
Neighbor : AWA.Countries.Models.Country_Neighbor_Ref;
begin
Neighbor.Set_Neighbor_Of (Country);
Neighbor.Set_Neighbor (Countries.Element (List (Pos .. N)));
Neighbor.Save (DB);
Count := Count + 1;
end;
else
Ada.Text_IO.Put_Line ("Country not found: " & List (Pos .. N));
end if;
Pos := N + 2;
end loop;
end;
Neighbors_Map.Next (Iter);
end loop;
Ada.Text_IO.Put_Line ("Created " & Natural'Image (Count) & " country neighbors");
end Build_Neighbors;
Count : constant Natural := Ada.Command_Line.Argument_Count;
Factory : ADO.Sessions.Factory.Session_Factory;
Parser : CSV_Parser;
begin
Util.Log.Loggers.Initialize ("log4j.properties");
if Count /= 1 then
Ada.Text_IO.Put_Line ("Usage: import_country file");
return;
end if;
-- Initialize the database drivers.
ADO.Drivers.Initialize ("am.properties");
-- Initialize the session factory to connect to the
-- database defined by 'ado.database' property.
Factory.Create (ADO.Drivers.Get_Config ("ado.database"));
DB := Factory.Get_Master_Session;
DB.Begin_Transaction;
declare
File : constant String := Ada.Command_Line.Argument (1);
begin
Parser.Set_Comment_Separator ('#');
Parser.Set_Field_Separator (ASCII.HT);
Parser.Parse (File);
Ada.Text_IO.Put_Line ("Found " & Count_Type'Image (Countries.Length) & " countries");
Build_Neighbors;
end;
DB.Commit;
end Import_Country;
|
-----------------------------------------------------------------------
-- import_country -- Read a Country csv file to update the database
-- 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.Text_IO;
with Ada.Command_Line;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with ADO;
with ADO.SQL;
with ADO.Drivers;
with ADO.Sessions;
with ADO.Statements;
with ADO.Sessions.Factory;
with Util.Strings;
with Util.Log.Loggers;
with Util.Serialize.IO.CSV;
with AWA.Countries.Models;
procedure Import_Country is
use Ada.Text_IO;
use Util.Serialize.IO.CSV;
use AWA.Countries.Models;
use Ada.Containers;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Import_Country");
Country : AWA.Countries.Models.Country_Ref;
DB : ADO.Sessions.Master_Session;
package Country_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => AWA.Countries.Models.Country_Ref,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
package Neighbors_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
Countries : Country_Map.Map;
Neighbors : Neighbors_Map.Map;
type CSV_Parser is new Util.Serialize.IO.CSV.Parser with null record;
overriding
procedure Set_Cell (Parser : in out CSV_Parser;
Value : in String;
Row : in Util.Serialize.IO.CSV.Row_Type;
Column : in Util.Serialize.IO.CSV.Column_Type);
overriding
procedure Set_Cell (Parser : in out CSV_Parser;
Value : in String;
Row : in Util.Serialize.IO.CSV.Row_Type;
Column : in Util.Serialize.IO.CSV.Column_Type) is
pragma Unreferenced (Parser, Row);
Query : ADO.SQL.Query;
Found : Boolean;
begin
case Column is
when 1 =>
-- The ISO code is unique, find the country
Query.Bind_Param (1, Value);
Query.Set_Filter ("iso_code = ?");
Country.Find (DB, Query, Found);
if not Found then
-- Build a new country object
Country := AWA.Countries.Models.Null_Country;
Country.Set_Iso_Code (Value);
end if;
Countries.Insert (Value, Country);
when 2 =>
-- Ada.Text_IO.Put_Line ("ISO3: " & Value);
null;
when 3 =>
-- Ada.Text_IO.Put_Line ("ISON: " & Value);
null;
when 4 =>
-- Ada.Text_IO.Put_Line ("FIPS: " & Value);
null;
-- Country name
when 5 =>
Country.Set_Name (Value);
when 6 =>
-- Ada.Text_IO.Put_Line ("Capital: " & Value);
null;
when 7 | 8 => -- Area, Population
null;
-- Country continent
when 9 =>
Country.Set_Continent (Value);
-- Country TLD
when 10 =>
Country.Set_Tld (Value);
-- Country CurrencyCode
when 11 =>
Country.Set_Currency_Code (Value);
-- Country CurrencyName
when 12 =>
Country.Set_Currency (Value);
when 13 | 14 => -- Phone, postal code format
null;
when 15 =>
-- Ada.Text_IO.Put_Line ("Postal regex: " & Value);
null;
-- Country languages
when 16 =>
Country.Set_Languages (Value);
-- Country unique geonameid
when 17 =>
if Value /= "" then
Country.Set_Geonameid (Integer'Value (Value));
end if;
when 18 =>
Country.Save (DB);
Neighbors.Insert (Country.Get_Iso_Code, Value);
when 19 => -- EquivalentFipsCode
null;
when others =>
null;
end case;
exception
when E : others =>
Log.Error ("Column " & Util.Serialize.IO.CSV.Column_Type'Image (Column)
& " value: " & Value, E, True);
raise;
end Set_Cell;
procedure Build_Neighbors is
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Countries.Models.COUNTRY_NEIGHBOR_TABLE);
Iter : Neighbors_Map.Cursor := Neighbors.First;
Count : Natural := 0;
begin
Stmt.Execute;
while Neighbors_Map.Has_Element (Iter) loop
declare
Name : constant String := Neighbors_Map.Key (Iter);
List : constant String := Neighbors_Map.Element (Iter);
Pos : Natural := List'First;
N : Natural;
begin
Country := Countries.Element (Name);
while Pos < List'Last loop
N := Util.Strings.Index (List, ',', Pos);
if N = 0 then
N := List'Last;
else
N := N - 1;
end if;
if Pos < N and then Countries.Contains (List (Pos .. N)) then
declare
Neighbor : AWA.Countries.Models.Country_Neighbor_Ref;
begin
Neighbor.Set_Neighbor_Of (Country);
Neighbor.Set_Neighbor (Countries.Element (List (Pos .. N)));
Neighbor.Save (DB);
Count := Count + 1;
end;
else
Ada.Text_IO.Put_Line ("Country not found: " & List (Pos .. N));
end if;
Pos := N + 2;
end loop;
end;
Neighbors_Map.Next (Iter);
end loop;
Ada.Text_IO.Put_Line ("Created " & Natural'Image (Count) & " country neighbors");
end Build_Neighbors;
Count : constant Natural := Ada.Command_Line.Argument_Count;
Factory : ADO.Sessions.Factory.Session_Factory;
Parser : CSV_Parser;
begin
if Count /= 2 then
Ada.Text_IO.Put_Line ("Usage: import_country config file");
return;
end if;
declare
Config : constant String := Ada.Command_Line.Argument (1);
begin
Util.Log.Loggers.Initialize (Config);
-- Initialize the database drivers.
ADO.Drivers.Initialize (Config);
-- Initialize the session factory to connect to the
-- database defined by 'ado.database' property.
Factory.Create (ADO.Drivers.Get_Config ("database"));
end;
DB := Factory.Get_Master_Session;
DB.Begin_Transaction;
declare
File : constant String := Ada.Command_Line.Argument (2);
begin
Parser.Set_Comment_Separator ('#');
Parser.Set_Field_Separator (ASCII.HT);
Parser.Parse (File);
Ada.Text_IO.Put_Line ("Found " & Count_Type'Image (Countries.Length) & " countries");
Build_Neighbors;
end;
DB.Commit;
end Import_Country;
|
Update the usage of the import tool
|
Update the usage of the import tool
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
cd3f1d82104725fc248093d64668f8d91c6ba24a
|
awa/src/awa-users-filters.adb
|
awa/src/awa-users-filters.adb
|
-----------------------------------------------------------------------
-- awa-users-beans -- ASF Beans for user module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Users.Services;
with AWA.Users.Module;
with AWA.Users.Principals;
with AWA.Users.Models;
package body AWA.Users.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("AWA.Users.Filters");
procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class;
User : in AWA.Users.Models.User_Ref;
Sess : in AWA.Users.Models.Session_Ref) is
Principal : constant Principals.Principal_Access := Principals.Create (User, Sess);
Session : ASF.Sessions.Session := Request.Get_Session (Create => True);
begin
Session.Set_Principal (Principal.all'Access);
end Set_Session_Principal;
-- ------------------------------
-- Initialize the filter and configure the redirection URIs.
-- ------------------------------
procedure Initialize (Filter : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
URI : constant String := Context.Get_Init_Parameter (AUTH_FILTER_REDIRECT_PARAM);
begin
Filter.Login_URI := To_Unbounded_String (URI);
end Initialize;
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
begin
null;
end Authenticate;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
overriding
procedure Do_Login (Filter : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
URI : constant String := To_String (Filter.Login_URI);
begin
Log.Info ("User is not logged, redirecting to {0}", URI);
if Request.Get_Header ("X-Requested-With") = "" then
Response.Send_Redirect (Location => URI);
else
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end if;
end Do_Login;
-- ------------------------------
-- Initialize the filter and configure the redirection URIs.
-- ------------------------------
procedure Initialize (Filter : in out Verify_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
URI : constant String := Context.Get_Init_Parameter ("user.verif-filter.redirect");
begin
Filter.Invalid_Key_URI := To_Unbounded_String (URI);
end Initialize;
-- ------------------------------
-- Filter a request which contains an access key and verify that the
-- key is valid and identifies a user. Once the user is known, create
-- a session and setup the user principal.
--
-- If the access key is missing or invalid, redirect to the
-- <b>Invalid_Key_URI</b> associated with the filter.
-- ------------------------------
overriding
procedure Do_Filter (Filter : in Verify_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
Key : constant String := Request.Get_Parameter ("key");
Manager : constant Users.Services.User_Service_Access := Users.Module.Get_User_Manager;
User : AWA.Users.Models.User_Ref;
Session : AWA.Users.Models.Session_Ref;
begin
Log.Info ("Verify access key {0}", Key);
Manager.Verify_User (Key => Key,
User => User,
IpAddr => "",
Session => Session);
Set_Session_Principal (Request, User, Session);
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
exception
when AWA.Users.Services.Not_Found =>
declare
URI : constant String := To_String (Filter.Invalid_Key_URI);
begin
Log.Info ("Invalid access key {0}, redirecting to {1}", Key, URI);
Response.Send_Redirect (Location => URI);
end;
end Do_Filter;
end AWA.Users.Filters;
|
-----------------------------------------------------------------------
-- awa-users-beans -- ASF Beans for user module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with AWA.Users.Services;
with AWA.Users.Module;
with AWA.Users.Principals;
with AWA.Users.Models;
package body AWA.Users.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("AWA.Users.Filters");
procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class;
User : in AWA.Users.Models.User_Ref;
Sess : in AWA.Users.Models.Session_Ref) is
Principal : constant Principals.Principal_Access := Principals.Create (User, Sess);
Session : ASF.Sessions.Session := Request.Get_Session (Create => True);
begin
Session.Set_Principal (Principal.all'Access);
end Set_Session_Principal;
-- ------------------------------
-- Initialize the filter and configure the redirection URIs.
-- ------------------------------
procedure Initialize (Filter : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
URI : constant String := Context.Get_Init_Parameter (AUTH_FILTER_REDIRECT_PARAM);
begin
Filter.Login_URI := To_Unbounded_String (URI);
end Initialize;
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
begin
null;
end Authenticate;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
overriding
procedure Do_Login (Filter : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
URI : constant String := To_String (Filter.Login_URI);
begin
Log.Info ("User is not logged, redirecting to {0}", URI);
if Request.Get_Header ("X-Requested-With") = "" then
Response.Send_Redirect (Location => URI);
else
Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED);
end if;
end Do_Login;
-- ------------------------------
-- Initialize the filter and configure the redirection URIs.
-- ------------------------------
procedure Initialize (Filter : in out Verify_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
URI : constant String := Context.Get_Init_Parameter (VERIFY_FILTER_REDIRECT_PARAM);
begin
Filter.Invalid_Key_URI := To_Unbounded_String (URI);
end Initialize;
-- ------------------------------
-- Filter a request which contains an access key and verify that the
-- key is valid and identifies a user. Once the user is known, create
-- a session and setup the user principal.
--
-- If the access key is missing or invalid, redirect to the
-- <b>Invalid_Key_URI</b> associated with the filter.
-- ------------------------------
overriding
procedure Do_Filter (Filter : in Verify_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
Key : constant String := Request.Get_Parameter (PARAM_ACCESS_KEY);
Manager : constant Users.Services.User_Service_Access := Users.Module.Get_User_Manager;
User : AWA.Users.Models.User_Ref;
Session : AWA.Users.Models.Session_Ref;
begin
Log.Info ("Verify access key {0}", Key);
Manager.Verify_User (Key => Key,
User => User,
IpAddr => "",
Session => Session);
Set_Session_Principal (Request, User, Session);
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
exception
when AWA.Users.Services.Not_Found =>
declare
URI : constant String := To_String (Filter.Invalid_Key_URI);
begin
Log.Info ("Invalid access key {0}, redirecting to {1}", Key, URI);
Response.Send_Redirect (Location => URI);
end;
end Do_Filter;
end AWA.Users.Filters;
|
Use declared constant values instead of inline strings.
|
Use declared constant values instead of inline strings.
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
79614be42c6b07ab53f9154d046c1db5d85fb0b1
|
src/security-oauth-clients.ads
|
src/security-oauth-clients.ads
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2013, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization.
--
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
package Security.OAuth.Clients is
-- ------------------------------
-- Access Token
-- ------------------------------
-- Access tokens are credentials used to access protected resources.
-- The access token is represented as a <b>Principal</b>. This is an opaque
-- value for an application.
type Access_Token (Len : Natural) is new Security.Principal with private;
type Access_Token_Access is access all Access_Token'Class;
-- Get the principal name. This is the OAuth access token.
function Get_Name (From : in Access_Token) return String;
type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private;
type OpenID_Token_Access is access all OpenID_Token'Class;
-- Get the id_token that was returned by the authentication process.
function Get_Id_Token (From : in OpenID_Token) return String;
-- Generate a random nonce with at last the number of random bits.
-- The number of bits is rounded up to a multiple of 32.
-- The random bits are then converted to base64url in the returned string.
function Create_Nonce (Bits : in Positive := 256) return String;
type Grant_Type is new Security.Principal with private;
-- Get the principal name. This is the OAuth access token.
function Get_Name (From : in Grant_Type) return String;
-- Get the Authorization header to be used for accessing a protected resource.
-- (See RFC 6749 7. Accessing Protected Resources)
function Get_Authorization (From : in Grant_Type) return String;
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is new Security.OAuth.Application with private;
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
procedure Set_Provider_URI (App : in out Application;
URI : in String);
-- OAuth 2.0 Section 4.1.1 Authorization Request
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
function Get_State (App : in Application;
Nonce : in String) return String;
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String;
-- OAuth 2.0 Section 4.1.2 Authorization Response
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean;
-- OAuth 2.0 Section 4.1.3. Access Token Request
-- Section 4.1.4. Access Token Response
-- Exchange the OAuth code into an access token.
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access;
-- Get a request token with username and password.
-- RFC 6749: 4.3. Resource Owner Password Credentials Grant
procedure Request_Token (App : in Application;
Username : in String;
Password : in String;
Scope : in String;
Token : in out Grant_Type'Class);
-- Refresh the access token.
-- RFC 6749: 6. Refreshing an Access Token
procedure Refresh_Token (App : in Application;
Scope : in String;
Token : in out Grant_Type'Class);
-- Create the access token
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access;
private
type Access_Token (Len : Natural) is new Security.Principal with record
Access_Id : String (1 .. Len);
end record;
type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record
Id_Token : String (1 .. Id_Len);
Refresh_Token : String (1 .. Refresh_Len);
end record;
type Application is new Security.OAuth.Application with record
Request_URI : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Grant_Type is new Security.Principal with record
Access_Token : Ada.Strings.Unbounded.Unbounded_String;
Refresh_Token : Ada.Strings.Unbounded.Unbounded_String;
Id_Token : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth.Clients;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2013, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- = OAuth2 Client =
-- The `Security.OAuth.Clients` package implements the client OAuth 2.0 authorization.
--
-- == Application setup ==
-- For an OAuth2 client application to authenticate, it must be registered on the server
-- and the server provides the following information:
--
-- * **client_id**: the client identifier is a unique string that identifies the application.
-- * **client_secret** the client secret is a secret shared between the server and the
-- client application. The client secret is optional.
--
-- The `Security.OAuth.Clients.Application` tagged record is the primary type that
-- allows to perform one of the OAuth 2.0 authorization flows. It is necessary to
-- declare an `Application` instance and register the **client_id**, the **client_secret**
-- and the authorisation URLs to connect to the server.
--
-- App : Security.OAuth.Clients.Application;
-- ...
-- App.Set_Application_Identifier ("app-identifier");
-- App.Set_Application_Secret ("app-secret");
-- App.Set_Provider_URL ("https://graph.facebook.com/oauth/access_token");
--
--
-- == Resource Owner Password Credentials Grant ==
-- The RFC 6749: 4.3. Resource Owner Password Credentials Grant allows to authorize an
-- application by using the user's name and password. This is the simplest OAuth flow
-- but because it requires to know the user's name and password, it is not recommended and
-- not supported by several servers. To use this authorization, the application will use
-- the `Request_Token` procedure and will give the user's name, password and the scope
-- of permissions. When the authorization succeeds, a `Grant_Type` token object is returned.
--
-- Token : Security.OAuth.Clients.Grant_Type;
-- ...
-- App.Request_Token ("admin", "admin", "scope", Token);
--
-- == Refreshing an access token ==
-- An access token has an expiration date and a new access token must be asked by using the
-- refresh token. When the access token has expired, the grant token object can be refreshed
-- to retrieve a new access token by using the `Refresh_Token` procedure. The scope of
-- permissions can also be passsed.
--
-- App.Refresh_Token ("scope", Token);
--
package Security.OAuth.Clients is
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
-- ------------------------------
-- Access Token
-- ------------------------------
-- Access tokens are credentials used to access protected resources.
-- The access token is represented as a <b>Principal</b>. This is an opaque
-- value for an application.
type Access_Token (Len : Natural) is new Security.Principal with private;
type Access_Token_Access is access all Access_Token'Class;
-- Get the principal name. This is the OAuth access token.
function Get_Name (From : in Access_Token) return String;
type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private;
type OpenID_Token_Access is access all OpenID_Token'Class;
-- Get the id_token that was returned by the authentication process.
function Get_Id_Token (From : in OpenID_Token) return String;
-- Generate a random nonce with at last the number of random bits.
-- The number of bits is rounded up to a multiple of 32.
-- The random bits are then converted to base64url in the returned string.
function Create_Nonce (Bits : in Positive := 256) return String;
type Grant_Type is new Security.Principal with private;
-- Get the principal name. This is the OAuth access token.
function Get_Name (From : in Grant_Type) return String;
-- Get the Authorization header to be used for accessing a protected resource.
-- (See RFC 6749 7. Accessing Protected Resources)
function Get_Authorization (From : in Grant_Type) return String;
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is new Security.OAuth.Application with private;
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
procedure Set_Provider_URI (App : in out Application;
URI : in String);
-- OAuth 2.0 Section 4.1.1 Authorization Request
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
function Get_State (App : in Application;
Nonce : in String) return String;
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String;
-- OAuth 2.0 Section 4.1.2 Authorization Response
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean;
-- OAuth 2.0 Section 4.1.3. Access Token Request
-- Section 4.1.4. Access Token Response
-- Exchange the OAuth code into an access token.
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access;
-- Get a request token with username and password.
-- RFC 6749: 4.3. Resource Owner Password Credentials Grant
procedure Request_Token (App : in Application;
Username : in String;
Password : in String;
Scope : in String;
Token : in out Grant_Type'Class);
-- Refresh the access token.
-- RFC 6749: 6. Refreshing an Access Token
procedure Refresh_Token (App : in Application;
Scope : in String;
Token : in out Grant_Type'Class);
-- Create the access token
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access;
private
type Access_Token (Len : Natural) is new Security.Principal with record
Access_Id : String (1 .. Len);
end record;
type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record
Id_Token : String (1 .. Id_Len);
Refresh_Token : String (1 .. Refresh_Len);
end record;
type Application is new Security.OAuth.Application with record
Request_URI : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Grant_Type is new Security.Principal with record
Access_Token : Ada.Strings.Unbounded.Unbounded_String;
Refresh_Token : Ada.Strings.Unbounded.Unbounded_String;
Id_Token : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth.Clients;
|
Add some documentation on OAuth
|
Add some documentation on OAuth
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
f80024d8da930efdc698d80a9065d23081e684fc
|
src/security-oauth-servers.ads
|
src/security-oauth-servers.ads
|
-----------------------------------------------------------------------
-- security-oauth-servers -- OAuth Server Authentication Support
-- Copyright (C) 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Strings;
with Security.Auth;
with Security.Permissions;
-- == OAuth Server ==
-- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package.
-- This package allows to implement the authorization framework described in RFC 6749
-- The OAuth 2.0 Authorization Framework.
--
-- The authorization method produce a <tt>Grant_Type</tt> object that contains the result
-- of the grant (successful or denied). It is the responsibility of the caller to format
-- the result in JSON/XML and return it to the client.
--
-- Three important operations are defined for the OAuth 2.0 framework.
--
-- <tt>Authorize</tt> is used to obtain an authorization request. This operation is
-- optional in the OAuth 2.0 framework since some authorization method directly return
-- the access token. This operation is used by the "Authorization Code Grant" and the
-- "Implicit Grant".
--
-- <tt>Token</tt> is used to get the access token and optional refresh token.
--
-- <tt>Authenticate</tt> is used for the API request to verify the access token
-- and authenticate the API call.
-- Several grant types are supported.
--
-- === Application Manager ===
-- The application manager maintains the repository of applications which are known by
-- the server and which can request authorization. Each application is identified by
-- a client identifier (represented by the <tt>client_id</tt> request parameter).
-- The application defines the authorization methods which are allowed as well as
-- the parameters to control and drive the authorization. This includes the redirection
-- URI, the application secret, the expiration delay for the access token.
--
-- The application manager is implemented by the application server and it must
-- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt>
-- method. The <tt>Find_Application</tt> is one of the first call made during the
-- authenticate and token generation phases.
--
-- === Resource Owner Password Credentials Grant ===
-- The password grant is one of the easiest grant method to understand but it is also one
-- of the less secure. In this grant method, the username and user password are passed in
-- the request parameter together with the application client identifier. The realm verifies
-- the username and password and when they are correct it generates the access token with
-- an optional refresh token.
--
-- Realm : Security.OAuth.Servers.Manager;
-- Grant : Security.OAuth.Servers.Grant_Type;
--
-- Realm.Authorize (Params, Grant);
--
-- === Accessing Protected Resources ===
-- When accessing a protected resource, the API implementation will use the
-- <tt>Authenticate</tt> operation to verify the access token and get a security principal.
-- The security principal will identifies the resource owner as well as the application
-- that is doing the call.
--
-- Realm : Security.OAuth.Servers.Manager;
-- Auth : Security.Principal_Access;
-- Token : String := ...;
--
-- Realm.Authenticate (Token, Auth);
--
-- When a security principal is returned, the access token was validated and the
-- request is granted for the application.
--
package Security.OAuth.Servers is
Invalid_Application : exception;
type Application is new Security.OAuth.Application with private;
-- Check if the application has the given permission.
function Has_Permission (App : in Application;
Permission : in Security.Permissions.Permission_Index) return Boolean;
-- Define the status of the grant.
type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant,
Stealed_Grant, Valid_Grant);
-- Define the grant type.
type Grant_Kind is (No_Grant, Access_Grant, Code_Grant,
Implicit_Grant, Password_Grant, Credential_Grant,
Extension_Grant);
-- The <tt>Grant_Type</tt> holds the results of the authorization.
-- When the grant is refused, the type holds information about the refusal.
type Grant_Type is record
-- The request grant type.
Request : Grant_Kind := No_Grant;
-- The response status.
Status : Grant_Status := Invalid_Grant;
-- When success, the token to return.
Token : Ada.Strings.Unbounded.Unbounded_String;
-- When success, the token expiration date.
Expires : Ada.Calendar.Time;
-- When success, the authentication principal.
Auth : Security.Principal_Access;
-- When error, the type of error to return.
Error : Util.Strings.Name_Access;
end record;
type Application_Manager is limited interface;
type Application_Manager_Access is access all Application_Manager'Class;
-- Find the application that correspond to the given client id.
-- The <tt>Invalid_Application</tt> exception should be raised if there is no such application.
function Find_Application (Realm : in Application_Manager;
Client_Id : in String) return Application'Class is abstract;
type Realm_Manager is limited interface;
type Realm_Manager_Access is access all Realm_Manager'Class;
-- Authenticate the token and find the associated authentication principal.
-- The access token has been verified and the token represents the identifier
-- of the Tuple (client_id, user, session) that describes the authentication.
-- The <tt>Authenticate</tt> procedure should look in its database (internal
-- or external) to find the authentication principal that was granted for
-- the token Tuple. When the token was not found (because it was revoked),
-- the procedure should return a null principal. If the authentication
-- principal can be cached, the <tt>Cacheable</tt> value should be set.
-- In that case, the access token and authentication principal are inserted
-- in a cache.
procedure Authenticate (Realm : in out Realm_Manager;
Token : in String;
Auth : out Principal_Access;
Cacheable : out Boolean) is abstract;
-- Create an auth token string that identifies the given principal. The returned
-- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The
-- returned token does not need to be signed. It will be inserted in the public part
-- of the returned access token.
function Authorize (Realm : in Realm_Manager;
App : in Application'Class;
Scope : in String;
Auth : in Principal_Access) return String is abstract;
procedure Verify (Realm : in Realm_Manager;
Username : in String;
Password : in String;
Auth : out Principal_Access) is abstract;
procedure Verify (Realm : in Realm_Manager;
Token : in String;
Auth : out Principal_Access) is abstract;
procedure Revoke (Realm : in Realm_Manager;
Auth : in Principal_Access) is abstract;
type Auth_Manager is tagged limited private;
type Auth_Manager_Access is access all Auth_Manager'Class;
-- Set the auth private key.
procedure Set_Private_Key (Manager : in out Auth_Manager;
Key : in String);
-- Set the application manager to use and and applications.
procedure Set_Application_Manager (Manager : in out Auth_Manager;
Repository : in Application_Manager_Access);
-- Set the realm manager to authentify users.
procedure Set_Realm_Manager (Manager : in out Auth_Manager;
Realm : in Realm_Manager_Access);
-- Authorize the access to the protected resource by the application and for the
-- given principal. The resource owner has been verified and is represented by the
-- <tt>Auth</tt> principal. Extract from the request parameters represented by
-- <tt>Params</tt> the application client id, the scope and the expected response type.
-- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749.
procedure Authorize (Realm : in out Auth_Manager;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
procedure Token (Realm : in out Auth_Manager;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
-- Make the access token from the authorization code that was created by the
-- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the
-- client secret and the validity of the authorization code. Extract from the
-- authorization code the auth principal that was used for the grant and make the
-- access token.
procedure Token_From_Code (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
procedure Authorize_Code (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
procedure Authorize_Token (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
-- Make the access token from the resource owner password credentials. The username,
-- password and scope are extracted from the request and they are verified through the
-- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the
-- principal describes the authorization and it is used to forge the access token.
-- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant.
procedure Token_From_Password (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
-- RFC 6749: 5. Issuing an Access Token
procedure Create_Token (Realm : in Auth_Manager;
Ident : in String;
Grant : in out Grant_Type);
-- Authenticate the access token and get a security principal that identifies the app/user.
-- See RFC 6749, 7. Accessing Protected Resources.
-- The access token is first searched in the cache. If it was found, it means the access
-- token was already verified in the past, it is granted and associated with a principal.
-- Otherwise, we have to verify the token signature first, then the expiration date and
-- we extract from the token public part the auth identification. The <tt>Authenticate</tt>
-- operation is then called to obtain the principal from the auth identification.
-- When access token is invalid or authentification cannot be verified, a null principal
-- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason
-- of failures (if any).
procedure Authenticate (Realm : in out Auth_Manager;
Token : in String;
Grant : out Grant_Type);
procedure Revoke (Realm : in out Auth_Manager;
Token : in String);
private
use Ada.Strings.Unbounded;
function Format_Expire (Expire : in Ada.Calendar.Time) return String;
type Application is new Security.OAuth.Application with record
Expire_Timeout : Duration;
Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET;
end record;
type Cache_Entry is record
Expire : Ada.Calendar.Time;
Auth : Principal_Access;
end record;
package Cache_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Cache_Entry,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
-- The access token cache is used to speed up the access token verification
-- when a request to a protected resource is made.
protected type Token_Cache is
procedure Authenticate (Token : in String;
Grant : in out Grant_Type);
procedure Insert (Token : in String;
Expire : in Ada.Calendar.Time;
Principal : in Principal_Access);
procedure Remove (Token : in String);
procedure Timeout;
private
Entries : Cache_Map.Map;
end Token_Cache;
type Auth_Manager is new Ada.Finalization.Limited_Controlled with record
-- The repository of applications.
Repository : Application_Manager_Access;
-- The realm for user authentication.
Realm : Realm_Manager_Access;
-- The server private key used by the HMAC signature.
Private_Key : Ada.Strings.Unbounded.Unbounded_String;
-- The access token cache.
Cache : Token_Cache;
-- The expiration time for the generated authorization code.
Expire_Code : Duration := 300.0;
end record;
-- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>)
type Token_Validity is record
Status : Grant_Status := Invalid_Grant;
Ident_Start : Natural := 0;
Ident_End : Natural := 0;
Expire : Ada.Calendar.Time;
end record;
function Validate (Realm : in Auth_Manager;
Client_Id : in String;
Token : in String) return Token_Validity;
end Security.OAuth.Servers;
|
-----------------------------------------------------------------------
-- security-oauth-servers -- OAuth Server Authentication Support
-- Copyright (C) 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with Util.Strings;
with Security.Auth;
with Security.Permissions;
-- == OAuth Server ==
-- OAuth server side is provided by the <tt>Security.OAuth.Servers</tt> package.
-- This package allows to implement the authorization framework described in RFC 6749
-- The OAuth 2.0 Authorization Framework.
--
-- The authorization method produce a <tt>Grant_Type</tt> object that contains the result
-- of the grant (successful or denied). It is the responsibility of the caller to format
-- the result in JSON/XML and return it to the client.
--
-- Three important operations are defined for the OAuth 2.0 framework.
--
-- <tt>Authorize</tt> is used to obtain an authorization request. This operation is
-- optional in the OAuth 2.0 framework since some authorization method directly return
-- the access token. This operation is used by the "Authorization Code Grant" and the
-- "Implicit Grant".
--
-- <tt>Token</tt> is used to get the access token and optional refresh token.
--
-- <tt>Authenticate</tt> is used for the API request to verify the access token
-- and authenticate the API call.
-- Several grant types are supported.
--
-- === Application Manager ===
-- The application manager maintains the repository of applications which are known by
-- the server and which can request authorization. Each application is identified by
-- a client identifier (represented by the <tt>client_id</tt> request parameter).
-- The application defines the authorization methods which are allowed as well as
-- the parameters to control and drive the authorization. This includes the redirection
-- URI, the application secret, the expiration delay for the access token.
--
-- The application manager is implemented by the application server and it must
-- implement the <tt>Application_Manager</tt> interface with the <tt>Find_Application</tt>
-- method. The <tt>Find_Application</tt> is one of the first call made during the
-- authenticate and token generation phases.
--
-- === Resource Owner Password Credentials Grant ===
-- The password grant is one of the easiest grant method to understand but it is also one
-- of the less secure. In this grant method, the username and user password are passed in
-- the request parameter together with the application client identifier. The realm verifies
-- the username and password and when they are correct it generates the access token with
-- an optional refresh token.
--
-- Realm : Security.OAuth.Servers.Manager;
-- Grant : Security.OAuth.Servers.Grant_Type;
--
-- Realm.Authorize (Params, Grant);
--
-- === Accessing Protected Resources ===
-- When accessing a protected resource, the API implementation will use the
-- <tt>Authenticate</tt> operation to verify the access token and get a security principal.
-- The security principal will identifies the resource owner as well as the application
-- that is doing the call.
--
-- Realm : Security.OAuth.Servers.Manager;
-- Auth : Security.Principal_Access;
-- Token : String := ...;
--
-- Realm.Authenticate (Token, Auth);
--
-- When a security principal is returned, the access token was validated and the
-- request is granted for the application.
--
package Security.OAuth.Servers is
Invalid_Application : exception;
type Application is new Security.OAuth.Application with private;
-- Check if the application has the given permission.
function Has_Permission (App : in Application;
Permission : in Security.Permissions.Permission_Index) return Boolean;
-- Define the status of the grant.
type Grant_Status is (Invalid_Grant, Expired_Grant, Revoked_Grant,
Stealed_Grant, Valid_Grant);
-- Define the grant type.
type Grant_Kind is (No_Grant, Access_Grant, Code_Grant,
Implicit_Grant, Password_Grant, Credential_Grant,
Extension_Grant);
-- The <tt>Grant_Type</tt> holds the results of the authorization.
-- When the grant is refused, the type holds information about the refusal.
type Grant_Type is record
-- The request grant type.
Request : Grant_Kind := No_Grant;
-- The response status.
Status : Grant_Status := Invalid_Grant;
-- When success, the token to return.
Token : Ada.Strings.Unbounded.Unbounded_String;
-- When success, the token expiration date.
Expires : Ada.Calendar.Time;
-- When success, the authentication principal.
Auth : Security.Principal_Access;
-- When error, the type of error to return.
Error : Util.Strings.Name_Access;
end record;
type Application_Manager is limited interface;
type Application_Manager_Access is access all Application_Manager'Class;
-- Find the application that correspond to the given client id.
-- The <tt>Invalid_Application</tt> exception should be raised if there is no such application.
function Find_Application (Realm : in Application_Manager;
Client_Id : in String) return Application'Class is abstract;
type Realm_Manager is limited interface;
type Realm_Manager_Access is access all Realm_Manager'Class;
-- Authenticate the token and find the associated authentication principal.
-- The access token has been verified and the token represents the identifier
-- of the Tuple (client_id, user, session) that describes the authentication.
-- The <tt>Authenticate</tt> procedure should look in its database (internal
-- or external) to find the authentication principal that was granted for
-- the token Tuple. When the token was not found (because it was revoked),
-- the procedure should return a null principal. If the authentication
-- principal can be cached, the <tt>Cacheable</tt> value should be set.
-- In that case, the access token and authentication principal are inserted
-- in a cache.
procedure Authenticate (Realm : in out Realm_Manager;
Token : in String;
Auth : out Principal_Access;
Cacheable : out Boolean) is abstract;
-- Create an auth token string that identifies the given principal. The returned
-- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The
-- returned token does not need to be signed. It will be inserted in the public part
-- of the returned access token.
function Authorize (Realm : in Realm_Manager;
App : in Application'Class;
Scope : in String;
Auth : in Principal_Access) return String is abstract;
procedure Verify (Realm : in Realm_Manager;
Username : in String;
Password : in String;
Auth : out Principal_Access) is abstract;
procedure Verify (Realm : in Realm_Manager;
Token : in String;
Auth : out Principal_Access) is abstract;
procedure Revoke (Realm : in out Realm_Manager;
Auth : in Principal_Access) is abstract;
type Auth_Manager is tagged limited private;
type Auth_Manager_Access is access all Auth_Manager'Class;
-- Set the auth private key.
procedure Set_Private_Key (Manager : in out Auth_Manager;
Key : in String);
-- Set the application manager to use and and applications.
procedure Set_Application_Manager (Manager : in out Auth_Manager;
Repository : in Application_Manager_Access);
-- Set the realm manager to authentify users.
procedure Set_Realm_Manager (Manager : in out Auth_Manager;
Realm : in Realm_Manager_Access);
-- Authorize the access to the protected resource by the application and for the
-- given principal. The resource owner has been verified and is represented by the
-- <tt>Auth</tt> principal. Extract from the request parameters represented by
-- <tt>Params</tt> the application client id, the scope and the expected response type.
-- Handle the "Authorization Code Grant" and "Implicit Grant" defined in RFC 6749.
procedure Authorize (Realm : in out Auth_Manager;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
procedure Token (Realm : in out Auth_Manager;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
-- Make the access token from the authorization code that was created by the
-- <tt>Authorize</tt> operation. Verify the client application, the redirect uri, the
-- client secret and the validity of the authorization code. Extract from the
-- authorization code the auth principal that was used for the grant and make the
-- access token.
procedure Token_From_Code (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
procedure Authorize_Code (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
procedure Authorize_Token (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Auth : in Security.Principal_Access;
Grant : out Grant_Type);
-- Make the access token from the resource owner password credentials. The username,
-- password and scope are extracted from the request and they are verified through the
-- <tt>Verify</tt> procedure to obtain an associated principal. When successful, the
-- principal describes the authorization and it is used to forge the access token.
-- This operation implements the RFC 6749: 4.3. Resource Owner Password Credentials Grant.
procedure Token_From_Password (Realm : in out Auth_Manager;
App : in Application'Class;
Params : in Security.Auth.Parameters'Class;
Grant : out Grant_Type);
-- RFC 6749: 5. Issuing an Access Token
procedure Create_Token (Realm : in Auth_Manager;
Ident : in String;
Grant : in out Grant_Type);
-- Authenticate the access token and get a security principal that identifies the app/user.
-- See RFC 6749, 7. Accessing Protected Resources.
-- The access token is first searched in the cache. If it was found, it means the access
-- token was already verified in the past, it is granted and associated with a principal.
-- Otherwise, we have to verify the token signature first, then the expiration date and
-- we extract from the token public part the auth identification. The <tt>Authenticate</tt>
-- operation is then called to obtain the principal from the auth identification.
-- When access token is invalid or authentification cannot be verified, a null principal
-- is returned. The <tt>Grant</tt> data will hold the result of the grant with the reason
-- of failures (if any).
procedure Authenticate (Realm : in out Auth_Manager;
Token : in String;
Grant : out Grant_Type);
procedure Revoke (Realm : in out Auth_Manager;
Token : in String);
private
use Ada.Strings.Unbounded;
function Format_Expire (Expire : in Ada.Calendar.Time) return String;
type Application is new Security.OAuth.Application with record
Expire_Timeout : Duration;
Permissions : Security.Permissions.Permission_Index_Set := Security.Permissions.EMPTY_SET;
end record;
type Cache_Entry is record
Expire : Ada.Calendar.Time;
Auth : Principal_Access;
end record;
package Cache_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Cache_Entry,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=",
"=" => "=");
-- The access token cache is used to speed up the access token verification
-- when a request to a protected resource is made.
protected type Token_Cache is
procedure Authenticate (Token : in String;
Grant : in out Grant_Type);
procedure Insert (Token : in String;
Expire : in Ada.Calendar.Time;
Principal : in Principal_Access);
procedure Remove (Token : in String);
procedure Timeout;
private
Entries : Cache_Map.Map;
end Token_Cache;
type Auth_Manager is new Ada.Finalization.Limited_Controlled with record
-- The repository of applications.
Repository : Application_Manager_Access;
-- The realm for user authentication.
Realm : Realm_Manager_Access;
-- The server private key used by the HMAC signature.
Private_Key : Ada.Strings.Unbounded.Unbounded_String;
-- The access token cache.
Cache : Token_Cache;
-- The expiration time for the generated authorization code.
Expire_Code : Duration := 300.0;
end record;
-- <expiration>.<client_id>.<auth-ident>.hmac(<public>.<private-key>)
type Token_Validity is record
Status : Grant_Status := Invalid_Grant;
Ident_Start : Natural := 0;
Ident_End : Natural := 0;
Expire : Ada.Calendar.Time;
end record;
function Validate (Realm : in Auth_Manager;
Client_Id : in String;
Token : in String) return Token_Validity;
end Security.OAuth.Servers;
|
Change Revoke to use in out parameter for the realm
|
Change Revoke to use in out parameter for the realm
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
e6057f0a217c16c1910e7fff8a869dea7d11a2b9
|
src/wiki-filters-toc.adb
|
src/wiki-filters-toc.adb
|
-----------------------------------------------------------------------
-- wiki-filters-toc -- Filter for the creation of Table Of Contents
-- Copyright (C) 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Fixed;
with Wiki.Nodes.Lists;
package body Wiki.Filters.TOC is
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
use Ada.Strings.Wide_Wide_Fixed;
First : Natural := Text'First;
Pos : Natural;
begin
while First <= Text'Last loop
Pos := Index (Text (First .. Text'Last), "__TOC__");
if Pos > 0 then
Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format);
Filter.Add_Node (Document, Wiki.Nodes.N_TOC_DISPLAY);
First := Pos + 7;
else
Pos := Index (Text (First .. Text'Last), "__NOTOC__");
if Pos > 0 then
Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format);
Document.Hide_TOC;
First := Pos + 9;
else
Filter_Type (Filter).Add_Text (Document, Text (First .. Text'Last), Format);
exit;
end if;
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
T : Wiki.Nodes.Lists.Node_List_Ref;
begin
Document.Get_TOC (T);
Wiki.Nodes.Lists.Append (T, new Wiki.Nodes.Node_Type '(Kind => Wiki.Nodes.N_TOC_ENTRY,
Len => Header'Length,
Header => Header,
Level => Level));
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
end Wiki.Filters.TOC;
|
-----------------------------------------------------------------------
-- wiki-filters-toc -- Filter for the creation of Table Of Contents
-- Copyright (C) 2016, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Fixed;
with Wiki.Nodes.Lists;
package body Wiki.Filters.TOC is
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
use Ada.Strings.Wide_Wide_Fixed;
First : Natural := Text'First;
Pos : Natural;
begin
while First <= Text'Last loop
Pos := Index (Text (First .. Text'Last), "__TOC__");
if Pos > 0 then
Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format);
Filter.Add_Node (Document, Wiki.Nodes.N_TOC_DISPLAY);
First := Pos + 7;
else
Pos := Index (Text (First .. Text'Last), "__NOTOC__");
if Pos > 0 then
Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format);
Document.Hide_TOC;
First := Pos + 9;
else
Filter_Type (Filter).Add_Text (Document, Text (First .. Text'Last), Format);
exit;
end if;
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out TOC_Filter;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
T : Wiki.Nodes.Lists.Node_List_Ref;
begin
Document.Get_TOC (T);
Wiki.Nodes.Lists.Append (T, new Wiki.Nodes.Node_Type '(Kind => Wiki.Nodes.N_TOC_ENTRY,
Len => Header'Length,
Header => Header,
Parent => null,
Level => Level));
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
end Wiki.Filters.TOC;
|
Update creation of TOC node
|
Update creation of TOC node
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
05b6dbe59313c796523bd40752b62eb643991d8c
|
src/wiki-render-html.adb
|
src/wiki-render-html.adb
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- 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 Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Html_Renderer;
Writer : in Wiki.Writers.Html_Writer_Type_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- 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;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Html_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
case Level is
when 1 =>
Document.Writer.Write_Wide_Element ("h1", Header);
when 2 =>
Document.Writer.Write_Wide_Element ("h2", Header);
when 3 =>
Document.Writer.Write_Wide_Element ("h3", Header);
when 4 =>
Document.Writer.Write_Wide_Element ("h4", Header);
when 5 =>
Document.Writer.Write_Wide_Element ("h5", Header);
when 6 =>
Document.Writer.Write_Wide_Element ("h6", Header);
when others =>
Document.Writer.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_Raw ("<br />");
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.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.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 an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
Document.Writer.Start_Element ("hr");
Document.Writer.End_Element ("hr");
end Add_Horizontal_Rule;
-- ------------------------------
-- 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
begin
Document.Writer.Start_Element (Ada.Characters.Conversions.To_String (To_Wide_Wide_String (Name)));
end Start_Element;
overriding
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String) is
begin
Document.Writer.End_Element (Ada.Characters.Conversions.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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Html_Renderer;
Writer : in Wiki.Writers.Html_Writer_Type_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- 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;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Html_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
case Level is
when 1 =>
Document.Writer.Write_Wide_Element ("h1", Header);
when 2 =>
Document.Writer.Write_Wide_Element ("h2", Header);
when 3 =>
Document.Writer.Write_Wide_Element ("h3", Header);
when 4 =>
Document.Writer.Write_Wide_Element ("h4", Header);
when 5 =>
Document.Writer.Write_Wide_Element ("h5", Header);
when 6 =>
Document.Writer.Write_Wide_Element ("h6", Header);
when others =>
Document.Writer.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_Raw ("<br />");
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.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.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 an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
Document.Writer.Start_Element ("hr");
Document.Writer.End_Element ("hr");
end Add_Horizontal_Rule;
-- ------------------------------
-- 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
begin
if Name = "p" then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
Document.Writer.Start_Element (Ada.Characters.Conversions.To_String (To_Wide_Wide_String (Name)));
end Start_Element;
overriding
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String) is
begin
if Name = "p" then
Document.Has_Paragraph := False;
Document.Need_Paragraph := True;
end if;
Document.Writer.End_Element (Ada.Characters.Conversions.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;
|
Handle "p" HTML elements to avoid creating spurious paragraphs when some HTML is embedded in the wiki text
|
Handle "p" HTML elements to avoid creating spurious paragraphs when
some HTML is embedded in the wiki text
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
b12346fc362805b415cb2083d89c916f8dfceab9
|
src/sqlite/ado-drivers-connections-sqlite.ads
|
src/sqlite/ado-drivers-connections-sqlite.ads
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Interfaces.C;
package ADO.Drivers.Connections.Sqlite is
subtype Sqlite_Access is System.Address;
-- The database connection manager
type Sqlite_Driver is limited private;
-- Initialize the SQLite driver.
procedure Initialize;
-- Check for an error after executing a sqlite statement.
procedure Check_Error (Connection : in Sqlite_Access;
Result : in Interfaces.C.int);
private
-- Database connection implementation
type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record
Server : aliased Sqlite_Access;
Name : Unbounded_String;
end record;
type Database_Connection_Access is access all Database_Connection'Class;
-- Get the database driver which manages this connection.
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access;
-- Create a delete statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access;
-- Create an insert statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access;
-- Create an update statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access;
-- Start a transaction.
overriding
procedure Begin_Transaction (Database : in out Database_Connection);
-- Commit the current transaction.
overriding
procedure Commit (Database : in out Database_Connection);
-- Rollback the current transaction.
overriding
procedure Rollback (Database : in out Database_Connection);
-- Load the database schema definition for the current database.
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition);
-- Closes the database connection
overriding
procedure Close (Database : in out Database_Connection);
-- Releases the sqlite connection if it is open
overriding
procedure Finalize (Database : in out Database_Connection);
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String);
type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record;
-- Create a new SQLite connection using the configuration parameters.
overriding
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : out ADO.Drivers.Connections.Database_Connection_Access);
end ADO.Drivers.Connections.Sqlite;
|
-----------------------------------------------------------------------
-- ADO Sqlite Database -- SQLite Database connections
-- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Interfaces.C;
package ADO.Drivers.Connections.Sqlite is
subtype Sqlite_Access is System.Address;
-- The database connection manager
type Sqlite_Driver is limited private;
-- Initialize the SQLite driver.
procedure Initialize;
-- Check for an error after executing a sqlite statement.
procedure Check_Error (Connection : in Sqlite_Access;
Result : in Interfaces.C.int);
private
-- Database connection implementation
type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record
Server : aliased Sqlite_Access;
Name : Unbounded_String;
end record;
type Database_Connection_Access is access all Database_Connection'Class;
-- Get the database driver which manages this connection.
overriding
function Get_Driver (Database : in Database_Connection)
return Driver_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access;
overriding
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access;
-- Create a delete statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access;
-- Create an insert statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access;
-- Create an update statement.
overriding
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access;
-- Start a transaction.
overriding
procedure Begin_Transaction (Database : in out Database_Connection);
-- Commit the current transaction.
overriding
procedure Commit (Database : in out Database_Connection);
-- Rollback the current transaction.
overriding
procedure Rollback (Database : in out Database_Connection);
-- Load the database schema definition for the current database.
overriding
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition);
-- Closes the database connection
overriding
procedure Close (Database : in out Database_Connection);
-- Releases the sqlite connection if it is open
overriding
procedure Finalize (Database : in out Database_Connection);
procedure Execute (Database : in out Database_Connection;
SQL : in Query_String);
type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record;
-- Create a new SQLite connection using the configuration parameters.
overriding
procedure Create_Connection (D : in out Sqlite_Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class);
end ADO.Drivers.Connections.Sqlite;
|
Update the Create_Connection procedure
|
Update the Create_Connection procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
539eb14181a785a93b82e9360ecebc07bd6607f1
|
awa/plugins/awa-images/src/awa-images-beans.ads
|
awa/plugins/awa-images/src/awa-images-beans.ads
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- 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 ADO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Storages.Beans;
with AWA.Images.Models;
with AWA.Images.Modules;
package AWA.Images.Beans is
-- ------------------------------
-- Image List Bean
-- ------------------------------
-- This bean represents a list of images for a given folder.
type Image_List_Bean is new AWA.Storages.Beans.Storage_List_Bean with record
-- List of images.
Image_List : aliased AWA.Images.Models.Image_Info_List_Bean;
Image_List_Bean : AWA.Images.Models.Image_Info_List_Bean_Access;
end record;
type Image_List_Bean_Access is access all Image_List_Bean'Class;
-- Load the list of images associated with the current folder.
overriding
procedure Load_Files (Storage : in Image_List_Bean);
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Create the Image_List_Bean bean instance.
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Images.Beans;
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ADO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Storages.Beans;
with AWA.Images.Models;
with AWA.Images.Modules;
package AWA.Images.Beans is
-- ------------------------------
-- Image List Bean
-- ------------------------------
-- This bean represents a list of images for a given folder.
type Image_List_Bean is new AWA.Storages.Beans.Storage_List_Bean with record
-- List of images.
Image_List : aliased AWA.Images.Models.Image_Info_List_Bean;
Image_List_Bean : AWA.Images.Models.Image_Info_List_Bean_Access;
end record;
type Image_List_Bean_Access is access all Image_List_Bean'Class;
-- Load the list of images associated with the current folder.
overriding
procedure Load_Files (Storage : in Image_List_Bean);
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Create the Image_List_Bean bean instance.
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Image_Bean is new AWA.Images.Models.Image_Bean with record
Module : AWA.Images.Modules.Image_Module_Access;
end record;
type Image_Bean_Access is access all Image_Bean'Class;
overriding
procedure Load (Into : in out Image_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Image_Bean bean instance.
function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Images.Beans;
|
Define the Image_Bean type with the Load operation
|
Define the Image_Bean type with the Load operation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
007879a93e6e4b243dfea2edaaf8ca12c7985398
|
regtests/asf-contexts-writer-tests.adb
|
regtests/asf-contexts-writer-tests.adb
|
-----------------------------------------------------------------------
-- Writer Tests - Unit tests for ASF.Contexts.Writer
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
package body ASF.Contexts.Writer.Tests is
use Util.Tests;
procedure Free_Writer is
new Ada.Unchecked_Deallocation (Object => Test_Writer'Class,
Name => Test_Writer_Access);
procedure Initialize (Stream : in out Test_Writer;
Content_Type : in String;
Encoding : in String;
Size : in Natural) is
Output : ASF.Streams.Print_Stream;
begin
Stream.Content.Initialize (Size => Size);
Output.Initialize (Stream.Content'Unchecked_Access);
Stream.Initialize (Content_Type, Encoding, Output);
end Initialize;
overriding
procedure Write (Stream : in out Test_Writer;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
for I in Buffer'Range loop
Append (Stream.Response, Character'Val (Buffer (I)));
end loop;
end Write;
overriding
procedure Flush (Stream : in out Test_Writer) is
begin
Response_Writer (Stream).Flush;
Stream.Content.Read (Into => Stream.Response);
end Flush;
-- Set up performed before each test case
overriding
procedure Set_Up (T : in out Test) is
begin
T.Writer := new Test_Writer;
-- use a small buffer to test the flush
T.Writer.Initialize ("text/xml", "UTF-8", 1024);
end Set_Up;
-- Tear down performed after each test case
overriding
procedure Tear_Down (T : in out Test) is
begin
Free_Writer (T.Writer);
end Tear_Down;
-- Test the Start/Write/End_Element methods
procedure Test_Write_Element (T : in out Test) is
begin
T.Writer.Start_Element ("p");
T.Writer.Start_Element ("b");
T.Writer.Write_Element ("i", "italic within a bold");
T.Writer.End_Element ("b");
T.Writer.End_Element ("p");
T.Writer.Flush;
Assert_Equals (T, "<p><b><i>italic within a bold</i></b></p>",
T.Writer.Response);
T.Writer.Response := To_Unbounded_String ("");
T.Writer.Start_Element ("div");
T.Writer.Write_Attribute ("title", "A ""S&'%^&<>");
T.Writer.Write_Attribute ("id", "23");
T.Writer.End_Element ("div");
T.Writer.Flush;
Assert_Equals (T, "<div title=""A "S&'%^&<>"" id=""23""></div>",
T.Writer.Response);
end Test_Write_Element;
-- Test the Write_Char/Text methods
procedure Test_Write_Text (T : in out Test) is
use Ada.Calendar;
Start : Ada.Calendar.Time;
D : Duration;
begin
Start := Ada.Calendar.Clock;
T.Writer.Start_Element ("p");
T.Writer.Write_Char ('<');
T.Writer.Write_Char ('>');
T.Writer.Write_Char ('~');
T.Writer.Start_Element ("i");
T.Writer.Write_Text ("""A' <>&");
T.Writer.End_Element ("i");
T.Writer.End_Element ("p");
T.Writer.Flush;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Write text: " & Duration'Image (D));
Assert_Equals (T, "<p><>~<i>""A' <>&</i></p>",
T.Writer.Response);
end Test_Write_Text;
package Caller is new Util.Test_Caller (Test, "Contexts.Writer");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Start_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.End_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Attribute",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Text",
Test_Write_Text'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Char",
Test_Write_Text'Access);
end Add_Tests;
end ASF.Contexts.Writer.Tests;
|
-----------------------------------------------------------------------
-- Writer Tests - Unit tests for ASF.Contexts.Writer
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
package body ASF.Contexts.Writer.Tests is
use Util.Tests;
procedure Free_Writer is
new Ada.Unchecked_Deallocation (Object => Test_Writer'Class,
Name => Test_Writer_Access);
procedure Initialize (Stream : in out Test_Writer;
Content_Type : in String;
Encoding : in String;
Size : in Natural) is
Output : ASF.Streams.Print_Stream;
begin
Stream.Content.Initialize (Size => Size);
Output.Initialize (Stream.Content'Unchecked_Access);
Stream.Initialize (Content_Type, Encoding, Output);
end Initialize;
overriding
procedure Write (Stream : in out Test_Writer;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
for I in Buffer'Range loop
Append (Stream.Response, Character'Val (Buffer (I)));
end loop;
end Write;
overriding
procedure Flush (Stream : in out Test_Writer) is
begin
Response_Writer (Stream).Flush;
Stream.Content.Flush (Into => Stream.Response);
end Flush;
-- Set up performed before each test case
overriding
procedure Set_Up (T : in out Test) is
begin
T.Writer := new Test_Writer;
-- use a small buffer to test the flush
T.Writer.Initialize ("text/xml", "UTF-8", 1024);
end Set_Up;
-- Tear down performed after each test case
overriding
procedure Tear_Down (T : in out Test) is
begin
Free_Writer (T.Writer);
end Tear_Down;
-- Test the Start/Write/End_Element methods
procedure Test_Write_Element (T : in out Test) is
begin
T.Writer.Start_Element ("p");
T.Writer.Start_Element ("b");
T.Writer.Write_Element ("i", "italic within a bold");
T.Writer.End_Element ("b");
T.Writer.End_Element ("p");
T.Writer.Flush;
Assert_Equals (T, "<p><b><i>italic within a bold</i></b></p>",
T.Writer.Response);
T.Writer.Response := To_Unbounded_String ("");
T.Writer.Start_Element ("div");
T.Writer.Write_Attribute ("title", "A ""S&'%^&<>");
T.Writer.Write_Attribute ("id", "23");
T.Writer.End_Element ("div");
T.Writer.Flush;
Assert_Equals (T, "<div title=""A "S&'%^&<>"" id=""23""></div>",
T.Writer.Response);
end Test_Write_Element;
-- Test the Write_Char/Text methods
procedure Test_Write_Text (T : in out Test) is
use Ada.Calendar;
Start : Ada.Calendar.Time;
D : Duration;
begin
Start := Ada.Calendar.Clock;
T.Writer.Start_Element ("p");
T.Writer.Write_Char ('<');
T.Writer.Write_Char ('>');
T.Writer.Write_Char ('~');
T.Writer.Start_Element ("i");
T.Writer.Write_Text ("""A' <>&");
T.Writer.End_Element ("i");
T.Writer.End_Element ("p");
T.Writer.Flush;
D := Ada.Calendar.Clock - Start;
Ada.Text_IO.Put_Line ("Write text: " & Duration'Image (D));
Assert_Equals (T, "<p><>~<i>""A' <>&</i></p>",
T.Writer.Response);
end Test_Write_Text;
package Caller is new Util.Test_Caller (Test, "Contexts.Writer");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Start_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.End_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Element",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Attribute",
Test_Write_Element'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Text",
Test_Write_Text'Access);
Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Char",
Test_Write_Text'Access);
end Add_Tests;
end ASF.Contexts.Writer.Tests;
|
Update to use the Flush operation of Output_Buffer_Stream to get the stream content
|
Update to use the Flush operation of Output_Buffer_Stream to get the stream content
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
38dbf351405731baf8435ab1de82cd4da22dc949
|
openal-context.ads
|
openal-context.ads
|
with OpenAL.ALC_Thin;
package OpenAL.Context is
--
-- Types
--
type Device_t is private;
type Context_t is private;
Invalid_Device : constant Device_t;
Invalid_Context : constant Context_t;
Null_Context : constant Context_t;
type Format_t is (Mono_8, Stereo_8, Mono_16, Stereo_16);
--
-- API
--
-- proc_map : alcOpenDevice
function Open_Device
(Specifier : in String) return Device_t;
-- proc_map : alcOpenDevice
function Open_Default_Device return Device_t;
-- proc_map : alcCloseDevice
function Close_Device
(Device : in Device_t) return Boolean;
-- proc_map : alcCreateContext
function Create_Context
(Device : in Device_t) return Context_t;
-- proc_map : alcMakeContextCurrent
function Make_Context_Current
(Context : in Context_t) return Boolean;
-- proc_map : alcProcessContext
procedure Process_Context
(Context : in Context_t);
-- proc_map : alcSuspendContext
procedure Suspend_Context
(Context : in Context_t);
-- proc_map : alcDestroyContext
procedure Destroy_Context
(Context : in Context_t);
-- proc_map : alcGetCurrentContext
function Get_Current_Context return Context_t;
-- proc_map : alcGetContextsDevice
function Get_Context_Device (Context : in Context_t) return Device_t;
-- proc_map : alIsExtensionPresent
function Is_Extension_Present
(Device : in Device_t;
Name : in String) return Boolean;
private
type Device_t is record
Device_Data : ALC_Thin.Device_t;
Capture_Format : Format_t;
Capture : Boolean := False;
end record;
type Context_t is new ALC_Thin.Context_t;
Invalid_Device : constant Device_t := Device_t'
(Device_Data => ALC_Thin.Invalid_Device,
Capture_Format => Mono_8,
Capture => False);
Invalid_Context : constant Context_t := Context_t (ALC_Thin.Invalid_Context);
Null_Context : constant Context_t := Invalid_Context;
end OpenAL.Context;
|
with OpenAL.ALC_Thin;
package OpenAL.Context is
--
-- Types
--
type Device_t is private;
type Context_t is private;
Invalid_Device : constant Device_t;
Invalid_Context : constant Context_t;
Null_Context : constant Context_t;
type Format_t is (Mono_8, Stereo_8, Mono_16, Stereo_16);
--
-- API
--
-- proc_map : alcOpenDevice
function Open_Device
(Specifier : in String) return Device_t;
-- proc_map : alcOpenDevice
function Open_Default_Device return Device_t;
-- proc_map : alcCloseDevice
function Close_Device
(Device : in Device_t) return Boolean;
-- proc_map : alcCreateContext
function Create_Context
(Device : in Device_t) return Context_t;
-- proc_map : alcMakeContextCurrent
function Make_Context_Current
(Context : in Context_t) return Boolean;
-- proc_map : alcProcessContext
procedure Process_Context
(Context : in Context_t);
-- proc_map : alcSuspendContext
procedure Suspend_Context
(Context : in Context_t);
-- proc_map : alcDestroyContext
procedure Destroy_Context
(Context : in Context_t);
-- proc_map : alcGetCurrentContext
function Get_Current_Context return Context_t;
-- proc_map : alcGetContextsDevice
function Get_Context_Device (Context : in Context_t) return Device_t;
-- proc_map : alcIsExtensionPresent
function Is_Extension_Present
(Device : in Device_t;
Name : in String) return Boolean;
private
type Device_t is record
Device_Data : ALC_Thin.Device_t;
Capture_Format : Format_t;
Capture : Boolean := False;
end record;
type Context_t is new ALC_Thin.Context_t;
Invalid_Device : constant Device_t := Device_t'
(Device_Data => ALC_Thin.Invalid_Device,
Capture_Format => Mono_8,
Capture => False);
Invalid_Context : constant Context_t := Context_t (ALC_Thin.Invalid_Context);
Null_Context : constant Context_t := Invalid_Context;
end OpenAL.Context;
|
Fix proc_map
|
Fix proc_map
|
Ada
|
isc
|
io7m/coreland-openal-ada,io7m/coreland-openal-ada
|
323b753e68c447c53d5360792f21e5ba278e9d3c
|
samples/openid.adb
|
samples/openid.adb
|
-----------------------------------------------------------------------
-- openid -- Example of OpenID 2.0 Authentication
-- 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.Text_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with ASF.Server.Web;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Users;
with AWS.Net.SSL;
with ASF.Security.Servlets;
procedure Openid is
use ASF.Applications;
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
CONTEXT_PATH : constant String := "/openid";
CONFIG_PATH : constant String := "samples.properties";
App : aliased ASF.Applications.Main.Application;
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
return;
end if;
begin
C.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Factory);
App.Register ("samplesMsg", "samples");
App.Set_Global ("contextPath", "/openid");
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "openid");
App.Set_Global ("version", "0.1");
App.Set_Global ("user", Util.Beans.Objects.To_Object (Users.User'Access,
Util.Beans.Objects.STATIC));
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
-- Register the filters
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "files", Pattern => "*.jpg");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
-- Install the debug filter.
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.png");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.png");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.jpg");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.jpg");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/openid/auth/login.html");
WS.Start;
delay 600.0;
App.Close;
exception
when E : others =>
Ada.Text_IO.Put_Line ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Openid;
|
-----------------------------------------------------------------------
-- openid -- Example of OpenID 2.0 Authentication
-- 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 Ada.Text_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with ASF.Server.Web;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Users;
with AWS.Net.SSL;
with ASF.Security.Servlets;
procedure Openid is
use ASF.Applications;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
CONTEXT_PATH : constant String := "/openid";
CONFIG_PATH : constant String := "samples.properties";
App : aliased ASF.Applications.Main.Application;
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased ASF.Security.Servlets.Verify_Auth_Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
return;
end if;
begin
C.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Factory);
App.Register ("samplesMsg", "samples");
App.Set_Global ("contextPath", "/openid");
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "openid");
App.Set_Global ("version", "0.1");
App.Set_Global ("user", Util.Beans.Objects.To_Object (Users.User'Access,
Util.Beans.Objects.STATIC));
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
-- Register the filters
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "files", Pattern => "*.jpg");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
-- Install the debug filter.
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.png");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.png");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.jpg");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.jpg");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/openid/auth/login.html");
WS.Start;
delay 600.0;
App.Close;
exception
when E : others =>
Ada.Text_IO.Put_Line ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Openid;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
28133f94f698ea4e88753d8f41f00731cccdb820
|
regtests/ado-tests.adb
|
regtests/ado-tests.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Calendar;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with Regtests;
with Regtests.Simple.Model;
with Regtests.Images.Model;
with Util.Assertions;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
with Util.Test_Caller;
package body ADO.Tests is
use Util.Log;
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests");
package Caller is new Util.Test_Caller (Test, "ADO");
procedure Fail (T : in Test; Message : in String);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Fail (T : in Test; Message : in String) is
begin
T.Assert (False, Message);
end Fail;
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
Fail (T, "Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
Fail (T, "Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
-- ------------------------------
-- Test string insert.
-- ------------------------------
procedure Test_String (T : in out Test) is
use ADO.Objects;
use Ada.Strings.Unbounded;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
User : Regtests.Simple.Model.User_Ref;
Usr2 : Regtests.Simple.Model.User_Ref;
Name : Unbounded_String;
begin
for I in 1 .. 127 loop
Append (Name, Character'Val (I));
end loop;
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
DB.Begin_Transaction;
User.Set_Name (Name);
User.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Usr2.Load (DB, User.Get_Id);
Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name),
"Invalid name inserted for user");
end Test_String;
-- ------------------------------
-- Test blob insert.
-- ------------------------------
procedure Test_Blob (T : in out Test) is
use ADO.Objects;
use Ada.Streams;
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element);
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Img : Regtests.Images.Model.Image_Ref;
Size : constant Natural := 100;
Data : ADO.Blob_Ref := ADO.Create_Blob (Size);
Img2 : Regtests.Images.Model.Image_Ref;
begin
for I in 1 .. Size loop
Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255);
end loop;
DB.Begin_Transaction;
Img.Set_Image (Data);
Img.Set_Create_Date (Ada.Calendar.Clock);
Img.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
-- And verify that the blob data matches what we inserted.
Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len),
"Invalid blob length");
for I in 1 .. Data.Value.Len loop
Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I),
"Invalid blob content at " & Stream_Element_Offset'Image (I));
end loop;
-- Create a blob initialized with a file content.
Data := ADO.Create_Blob ("Makefile");
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob");
T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small");
end Test_Blob;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access);
Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access);
Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access);
Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access);
Caller.Add_Test (Suite, "Test insert string",
Test_String'Access);
Caller.Add_Test (Suite, "Test insert blob",
Test_Blob'Access);
end Add_Tests;
end ADO.Tests;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Calendar;
with ADO.Statements;
with ADO.Objects;
with ADO.Sessions;
with ADO.Utils;
with Regtests;
with Regtests.Simple.Model;
with Regtests.Images.Model;
with Util.Assertions;
with Util.Measures;
with Util.Log;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Test_Caller;
package body ADO.Tests is
use Util.Log;
use Ada.Exceptions;
use ADO.Statements;
use type Regtests.Simple.Model.User_Ref;
use type Regtests.Simple.Model.Allocate_Ref;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests");
package Caller is new Util.Test_Caller (Test, "ADO");
procedure Fail (T : in Test; Message : in String);
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence);
procedure Fail (T : in Test; Message : in String) is
begin
T.Assert (False, Message);
end Fail;
procedure Assert_Has_Message (T : in Test;
E : in Exception_Occurrence) is
Message : constant String := Exception_Message (E);
begin
Log.Info ("Exception: {0}", Message);
T.Assert (Message'Length > 0,
"Exception " & Exception_Name (E) & " does not have any message");
end Assert_Has_Message;
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Is_Null
-- ------------------------------
procedure Test_Load (T : in out Test) is
DB : ADO.Sessions.Session := Regtests.Get_Database;
Object : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null");
Object.Load (DB, -1);
T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception");
exception
when ADO.Objects.NOT_FOUND =>
T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object");
end Test_Load;
-- ------------------------------
-- Check:
-- Object_Ref.Load
-- Object_Ref.Save
-- <Model>.Set_xxx (Unbounded_String)
-- <Model>.Create
-- ------------------------------
procedure Test_Create_Load (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Object : Regtests.Simple.Model.User_Ref;
Check : Regtests.Simple.Model.User_Ref;
begin
-- Initialize and save an object
Object.Set_Name ("A simple test name");
Object.Save (DB);
T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier");
-- Load the object
Check.Load (DB, Object.Get_Id);
T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed");
end Test_Create_Load;
-- ------------------------------
-- Check:
-- Various error checks on database connections
--
-- Master_Connection.Rollback
-- ------------------------------
procedure Test_Not_Open (T : in out Test) is
DB : ADO.Sessions.Master_Session;
begin
begin
DB.Rollback;
Fail (T, "Master_Connection.Rollback should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
begin
DB.Commit;
Fail (T, "Master_Connection.Commit should raise an exception");
exception
when E : ADO.Sessions.NOT_OPEN =>
Assert_Has_Message (T, E);
end;
end Test_Not_Open;
-- ------------------------------
-- Check id generation
-- ------------------------------
procedure Test_Allocate (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE);
PrevId : Identifier := NO_IDENTIFIER;
S : Util.Measures.Stamp;
begin
for I in 1 .. 200 loop
declare
Obj : Regtests.Simple.Model.Allocate_Ref;
begin
Obj.Save (DB);
Key := Obj.Get_Key;
if PrevId /= NO_IDENTIFIER then
T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: "
& Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId));
end if;
PrevId := Objects.Get_Value (Key);
end;
end loop;
Util.Measures.Report (S, "Allocate 200 ids");
end Test_Allocate;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- Object.Find
-- Object.Save (update)
-- ------------------------------
procedure Test_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Ref : Regtests.Simple.Model.Allocate_Ref;
Ref2 : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
Ref.Set_Name ("Testing the allocation: update");
Ref.Save (DB);
Ref2.Load (DB, Ref.Get_Id);
end Test_Create_Save;
-- ------------------------------
-- Check:
-- Object.Save (with creation)
-- ------------------------------
procedure Test_Perf_Create_Save (T : in out Test) is
use ADO.Objects;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
S : Util.Measures.Stamp;
begin
DB.Begin_Transaction;
for I in 1 .. 1_000 loop
declare
Ref : Regtests.Simple.Model.Allocate_Ref;
begin
Ref.Set_Name ("Testing the allocation");
Ref.Save (DB);
T.Assert (Ref.Get_Id > 0, "Object must have an id");
end;
end loop;
DB.Commit;
Util.Measures.Report (S, "Create 1000 rows");
end Test_Perf_Create_Save;
procedure Test_Delete_All (T : in out Test) is
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
Result : Natural;
begin
DB.Begin_Transaction;
Stmt.Execute (Result);
Log.Info ("Deleted {0} rows", Natural'Image (Result));
DB.Commit;
T.Assert (Result > 100, "Too few rows were deleted");
end Test_Delete_All;
-- ------------------------------
-- Test string insert.
-- ------------------------------
procedure Test_String (T : in out Test) is
use ADO.Objects;
use Ada.Strings.Unbounded;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
User : Regtests.Simple.Model.User_Ref;
Usr2 : Regtests.Simple.Model.User_Ref;
Name : Unbounded_String;
begin
for I in 1 .. 127 loop
Append (Name, Character'Val (I));
end loop;
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
Append (Name, ' ');
DB.Begin_Transaction;
User.Set_Name (Name);
User.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Usr2.Load (DB, User.Get_Id);
Util.Tests.Assert_Equals (T, To_String (Name), String '(Usr2.Get_Name),
"Invalid name inserted for user");
end Test_String;
-- ------------------------------
-- Test blob insert.
-- ------------------------------
procedure Test_Blob (T : in out Test) is
use ADO.Objects;
use Ada.Streams;
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element);
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Img : Regtests.Images.Model.Image_Ref;
Size : constant Natural := 100;
Data : ADO.Blob_Ref := ADO.Create_Blob (Size);
Img2 : Regtests.Images.Model.Image_Ref;
begin
for I in 1 .. Size loop
Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255);
end loop;
DB.Begin_Transaction;
Img.Set_Image (Data);
Img.Set_Create_Date (Ada.Calendar.Clock);
Img.Save (DB);
DB.Commit;
-- Check that we can load the image and the blob.
Img2.Load (DB, Img.Get_Id);
T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded");
-- And verify that the blob data matches what we inserted.
Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len),
"Invalid blob length");
for I in 1 .. Data.Value.Len loop
Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I),
"Invalid blob content at " & Stream_Element_Offset'Image (I));
end loop;
-- Create a blob initialized with a file content.
Data := ADO.Create_Blob ("Makefile");
T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob");
T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small");
end Test_Blob;
-- ------------------------------
-- Test the To_Object and To_Identifier operations.
-- ------------------------------
procedure Test_Identifier_To_Object (T : in out Test) is
Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER);
begin
T.Assert (Util.Beans.Objects.Is_Null (Val),
"To_Object must return null for ADO.NO_IDENTIFIER");
T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER,
"To_Identifier must return ADO.NO_IDENTIFIER for null");
Val := ADO.Utils.To_Object (1);
T.Assert (not Util.Beans.Objects.Is_Null (Val),
"To_Object must not return null for a valid Identifier");
T.Assert (ADO.Utils.To_Identifier (Val) = 1,
"To_Identifier must return the correct identifier");
end Test_Identifier_To_Object;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access);
Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access);
Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update",
Test_Create_Save'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)",
Test_Perf_Create_Save'Access);
Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)",
Test_Delete_All'Access);
Caller.Add_Test (Suite, "Test insert string",
Test_String'Access);
Caller.Add_Test (Suite, "Test insert blob",
Test_Blob'Access);
Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier",
Test_Identifier_To_Object'Access);
end Add_Tests;
end ADO.Tests;
|
Add a test to check the ADO.Utils.To_Object and ADO.Utils.To_Identifier
|
Add a test to check the ADO.Utils.To_Object and ADO.Utils.To_Identifier
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
a4332c7fb40fa287db62ad2201dd78e43061e83f
|
arch/ARM/STM32/drivers/stm32-wwdg.ads
|
arch/ARM/STM32/drivers/stm32-wwdg.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017, 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. --
-- --
------------------------------------------------------------------------------
-- This package provides an interface to the on-board "window watchdog"
-- provided by the STM32F4 family.
-- Important: see Figure 215 in RM0090, the STM32 reference manual,
-- illustrating the watchdog behavior and significant events.
-- Note that time is increasing to the right in the figure.
-- www.st.com/resource/en/reference_manual/DM00031020.pdf
package STM32.WWDG is -- the Window Watchdog
pragma Elaborate_Body;
procedure Enable_Watchdog_Clock;
procedure Reset_Watchdog;
-- Resets the peripheral using the RCC
type Prescalers is
(Divider_1,
Divider_2,
Divider_4,
Divider_8)
with Size => 2;
-- These prescalers are clock frequency dividers, with numeric divisor
-- values corresponding to the digits in the names. The dividers are used
-- to determine the watchdog counter clock frequency driving the countdown
-- timer.
--
-- The frequency is computed as follows:
-- PCLK1 / 4096 / divider-value
-- For example, assuming PCLK1 of 45MHz and Divider_8, we'd get:
-- 45_000_000 / 4096 / 8 => 1373 Hz
--
-- The frequency can be used to calculate the time span values for the
-- refresh window, for example. See the demo program for doing that.
procedure Set_Watchdog_Prescaler (Value : Prescalers);
-- Set the divider used to derive the watchdog counter clock frequency
-- driving the countdown timer.
--
-- Note that the watchdog counter only counts down to 16#40# (64) before
-- triggering the reset, and the upper limit for the counter value is 127,
-- so there is a relatively limited number of counts available for the
-- refresh window to be open. Therefore, the frequency at which the
-- watchdog clock drives the counter is a significant factor in the
-- total possible time span for the refresh window.
subtype Downcounter is UInt7 range 16#40# .. UInt7'Last;
-- 16#40# is the last value of the countdown counter prior to a reset. When
-- the count goes to 16#3F# the high-oder bit being cleared triggers the
-- reset (if the watchdog is activated). Thus we never want to specify a
-- counter value less than 16#40#.
procedure Set_Watchdog_Window (Window_Start_Count : Downcounter);
-- Set the value of the countdown counter for when the refresh window is
-- to open. In figure 215, this is the counter value at the start of the
-- "refresh allowed" interval. It is an arbitrary, user-defined value.
--
-- The last counter value prior to reset is always 64 (16#40#). At 16#3F#
-- the high-order counter bit (T6 in the figure) clears, causing the
-- watchdog to trigger the system reset (when activated).
--
-- To prevent a reset, the watchdog counter must be refreshed by the
-- application but only when the counter is lower than Value and greater
-- than 16#3F#.
procedure Activate_Watchdog (New_Count : Downcounter);
-- Set the watchdog counter to begin counting down from New_Count and
-- activate the watchdog. In the figure, this is the counter value at
-- the start of the "refresh not allowed" interval. It is an arbitrary,
-- user-defined value.
--
-- Once activated there is no way to deactivate the watchdog other
-- than a system reset.
--
-- Note that, as a "window" watchdog, the period in which the counter can
-- be refreshed does not open immediately upon activating the watchdog.
procedure Refresh_Watchdog_Counter (New_Count : Downcounter);
-- Set the counter to begin counting down from New_Count. Used to refresh
-- the watchdog counter in order to prevent the watchdog timeout. In the
-- figure, this is the counter value at the start of the "refresh not
-- allowed" interval. It is an arbitrary, user-defined value, but is likely
-- the same value passed to Activate_Watchdog. The difference between this
-- routine and the activating routine is soley the activation.
procedure Enable_Early_Wakeup_Interrupt;
-- When enabled, an interrupt occurs whenever the counter reaches the value
-- 16#40#, ie one counter decrement period before the counter causes a
-- system reset. Once enabled, this interrupt can only be disabled by
-- hardware after a system reset.
function Early_Wakeup_Interrupt_Indicated return Boolean
with Inline;
-- Set by hardware when the counter has reached the value 16#40#, the
-- counter value just prior to the reset being triggered. Always set,
-- even if the interrupt is not enabled.
procedure Clear_Early_Wakeup_Interrupt
with Inline;
-- Clears the status bit
function WWDG_Reset_Indicated return Boolean;
-- Indicated in the RCC peripheral
procedure Clear_WWDG_Reset_Flag;
-- In the RCC peripheral
procedure Reset_System;
-- an immediate software-driven reset, just as if the count hit 16#3F#
end STM32.WWDG;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017, 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. --
-- --
------------------------------------------------------------------------------
-- This package provides an interface to the on-board "window watchdog"
-- provided by the STM32F4 family.
-- Important: see Figure 215 in RM0090, the STM32 reference manual,
-- illustrating the watchdog behavior and significant events.
-- Note that time is increasing to the right in the figure.
-- www.st.com/resource/en/reference_manual/DM00031020.pdf
package STM32.WWDG is -- the Window Watchdog
pragma Elaborate_Body;
procedure Enable_Watchdog_Clock;
procedure Reset_Watchdog;
-- Resets the peripheral using the RCC
type Prescalers is
(Divider_1,
Divider_2,
Divider_4,
Divider_8)
with Size => 2;
-- These prescalers are clock frequency dividers, with numeric divisor
-- values corresponding to the digits in the names. The dividers are used
-- to determine the watchdog counter clock frequency driving the countdown
-- timer.
--
-- The frequency is computed as follows:
-- PCLK1 / 4096 / divider-value
-- For example, assuming PCLK1 of 45MHz and Divider_8, we'd get:
-- 45_000_000 / 4096 / 8 => 1373 Hz
--
-- The frequency can be used to calculate the time span values for the
-- refresh window, for example. See the demo program for doing that.
procedure Set_Watchdog_Prescaler (Value : Prescalers);
-- Set the divider used to derive the watchdog counter clock frequency
-- driving the countdown timer.
--
-- Note that the watchdog counter only counts down to 16#40# (64) before
-- triggering the reset, and the upper limit for the counter value is 127,
-- so there is a relatively limited number of counts available for the
-- refresh window to be open. Therefore, the frequency at which the
-- watchdog clock drives the counter is a significant factor in the
-- total possible time span for the refresh window.
subtype Downcounter is UInt7 range 16#40# .. UInt7'Last;
-- 16#40# is the last value of the countdown counter prior to a reset. When
-- the count goes to 16#3F# the high-oder bit being cleared triggers the
-- reset (if the watchdog is activated). Thus we never want to specify a
-- counter value less than 16#40#.
procedure Set_Watchdog_Window (Window_Start_Count : Downcounter);
-- Set the value of the countdown counter for when the refresh window is
-- to open. In figure 215, this is the counter value at the start of the
-- "refresh allowed" interval. It is an arbitrary, user-defined value.
--
-- The last counter value prior to reset is always 64 (16#40#). At 16#3F#
-- the high-order counter bit (T6 in the figure) clears, causing the
-- watchdog to trigger the system reset (when activated).
--
-- To prevent a reset, the watchdog counter must be refreshed by the
-- application but only when the counter is lower than Window_Start_Count
-- and greater than 16#3F#.
procedure Activate_Watchdog (New_Count : Downcounter);
-- Set the watchdog counter to begin counting down from New_Count and
-- activate the watchdog. In the figure, this is the counter value at
-- the start of the "refresh not allowed" interval. It is an arbitrary,
-- user-defined value.
--
-- Once activated there is no way to deactivate the watchdog other
-- than a system reset.
--
-- Note that, as a "window" watchdog, the period in which the counter can
-- be refreshed does not open immediately upon activating the watchdog.
procedure Refresh_Watchdog_Counter (New_Count : Downcounter);
-- Set the counter to begin counting down from New_Count. Used to refresh
-- the watchdog counter in order to prevent the watchdog timeout. In the
-- figure, this is the counter value at the start of the "refresh not
-- allowed" interval. It is an arbitrary, user-defined value, but is likely
-- the same value passed to Activate_Watchdog. The difference between this
-- routine and the activating routine is soley the activation.
procedure Enable_Early_Wakeup_Interrupt;
-- When enabled, an interrupt occurs whenever the counter reaches the value
-- 16#40#, ie one counter decrement period before the counter causes a
-- system reset. Once enabled, this interrupt can only be disabled by
-- hardware after a system reset.
function Early_Wakeup_Interrupt_Indicated return Boolean
with Inline;
-- Set by hardware when the counter has reached the value 16#40#, the
-- counter value just prior to the reset being triggered. Always set,
-- even if the interrupt is not enabled.
procedure Clear_Early_Wakeup_Interrupt
with Inline;
-- Clears the status bit
function WWDG_Reset_Indicated return Boolean;
-- Indicated in the RCC peripheral
procedure Clear_WWDG_Reset_Flag;
-- In the RCC peripheral
procedure Reset_System;
-- an immediate software-driven reset, just as if the count hit 16#3F#
end STM32.WWDG;
|
fix name of formal parameter referenced in comment
|
fix name of formal parameter referenced in comment
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
e724b39d53382ce2e2832f34549abee2849844b6
|
awa/plugins/awa-tags/src/awa-tags.ads
|
awa/plugins/awa-tags/src/awa-tags.ads
|
-----------------------------------------------------------------------
-- awa-tags -- Tags management
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Tags</b> module allows to associate general purpose tags to any database entity.
-- It provides a JSF component that allows to insert easily a list of tags in a page and
-- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt>
-- to define the tags and it will use the <tt>awa:tagList</tt> component to display them.
-- A tag cloud is also provided by the <tt>awa:tagCloud</tt> component.
--
-- == Model ==
-- The database model is generic and it uses the <tt>Entity_Type</tt> provided by
-- [http://ada-ado.googlecode.com ADO] to associate a tag to entities stored in different
-- tables. The <tt>Entity_Type</tt> identifies the database table and the stored identifier
-- in <tt>for_entity_id</tt> defines the entity in that table.
--
-- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png]
--
-- @include awa-tags-modules.ads
-- @include awa-tags-beans.ads
-- @include awa-tags-components.ads
--
package AWA.Tags is
pragma Pure;
end AWA.Tags;
|
-----------------------------------------------------------------------
-- awa-tags -- Tags management
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Tags</b> module allows to associate general purpose tags to any database entity.
-- It provides a JSF component that allows to insert easily a list of tags in a page and
-- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt>
-- to define the tags and it will use the <tt>awa:tagList</tt> component to display them.
-- A tag cloud is also provided by the <tt>awa:tagCloud</tt> component.
--
-- == Model ==
-- The database model is generic and it uses the <tt>Entity_Type</tt> provided by
-- [http://ada-ado.googlecode.com ADO] to associate a tag to entities stored in different
-- tables. The <tt>Entity_Type</tt> identifies the database table and the stored identifier
-- in <tt>for_entity_id</tt> defines the entity in that table.
--
-- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png]
--
-- @include awa-tags-modules.ads
-- @include awa-tags-beans.ads
-- @include awa-tags-components.ads
--
-- == Queries ==
-- @include tag-queries.xml
package AWA.Tags is
pragma Pure;
end AWA.Tags;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7b900a7308fd108313dfa42a73acec1417bb7723
|
regtests/ado-parameters-tests.ads
|
regtests/ado-parameters-tests.ads
|
-----------------------------------------------------------------------
-- ado-parameters-tests -- Test query parameters and SQL expansion
-- 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 ADO.Parameters.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test expand SQL with parameters.
procedure Test_Expand_Sql (T : in out Test);
-- Test expand with invalid parameters.
procedure Test_Expand_Error (T : in out Test);
-- Test expand performance.
procedure Test_Expand_Perf (T : in out Test);
end ADO.Parameters.Tests;
|
-----------------------------------------------------------------------
-- ado-parameters-tests -- Test query parameters and SQL expansion
-- 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 Util.Tests;
package ADO.Parameters.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test expand SQL with parameters.
procedure Test_Expand_Sql (T : in out Test);
-- Test expand with invalid parameters.
procedure Test_Expand_Error (T : in out Test);
-- Test expand performance.
procedure Test_Expand_Perf (T : in out Test);
-- Test expand with cache expander.
procedure Test_Expand_With_Expander (T : in out Test);
end ADO.Parameters.Tests;
|
Declare the Test_Expand_With_Expander procedure
|
Declare the Test_Expand_With_Expander procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
0a593af49d67d0831127410f0904887fb4d45376
|
awa/awaunit/awa-tests.ads
|
awa/awaunit/awa-tests.ads
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Applications;
with AWA.Services.Filters;
with Util.Properties;
with Util.Tests;
with Util.XUnit;
with ASF.Filters.Dump;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Servlets.Measures;
package AWA.Tests is
type Test is abstract new Util.Tests.Test with null record;
-- Setup the service context before executing the test.
overriding
procedure Set_Up (T : in out Test);
-- Cleanup after the test execution.
overriding
procedure Tear_Down (T : in out Test);
-- Initialize the AWA test framework mockup.
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean);
-- Called when the testsuite execution has finished.
procedure Finish (Status : in Util.XUnit.Status);
procedure Initialize (Props : in Util.Properties.Manager);
-- Get the test application.
function Get_Application return AWA.Applications.Application_Access;
-- Set the application context to simulate a web request context.
procedure Set_Application_Context;
type Test_Application is new AWA.Applications.Application with record
Self : AWA.Applications.Application_Access;
-- Application servlets and filters (add new servlet and filter instances here).
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
end record;
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
overriding
procedure Initialize_Servlets (App : in out Test_Application);
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
overriding
procedure Initialize_Filters (App : in out Test_Application);
end AWA.Tests;
|
-----------------------------------------------------------------------
-- AWA tests - AWA Tests Framework
-- Copyright (C) 2011, 2012, 2014, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Applications;
with AWA.Services.Filters;
with Util.Properties;
with Util.Tests;
with Util.XUnit;
with ASF.Filters.Dump;
with ASF.Servlets.Faces;
with Servlet.Core.Files;
with ASF.Servlets.Ajax;
with Servlet.Core.Measures;
package AWA.Tests is
type Test is abstract new Util.Tests.Test with null record;
-- Setup the service context before executing the test.
overriding
procedure Set_Up (T : in out Test);
-- Cleanup after the test execution.
overriding
procedure Tear_Down (T : in out Test);
-- Initialize the AWA test framework mockup.
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean);
-- Called when the testsuite execution has finished.
procedure Finish (Status : in Util.XUnit.Status);
procedure Initialize (Props : in Util.Properties.Manager);
-- Get the test application.
function Get_Application return AWA.Applications.Application_Access;
-- Set the application context to simulate a web request context.
procedure Set_Application_Context;
type Test_Application is new AWA.Applications.Application with record
Self : AWA.Applications.Application_Access;
-- Application servlets and filters (add new servlet and filter instances here).
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Files : aliased Servlet.Core.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Measures : aliased Servlet.Core.Measures.Measure_Servlet;
end record;
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
overriding
procedure Initialize_Servlets (App : in out Test_Application);
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
overriding
procedure Initialize_Filters (App : in out Test_Application);
end AWA.Tests;
|
Use Servlet.Core packages instead of ASF.Servlets
|
Use Servlet.Core packages instead of ASF.Servlets
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f8def12b4d17723029da3fbaf1de3fd4ffab90a7
|
src/wiki-nodes.ads
|
src/wiki-nodes.ads
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Strings;
with Util.Refs;
package Wiki.Nodes is
pragma Preelaborate;
type Node_Kind is (N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_HEADER,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_PREFORMAT,
N_LIST,
N_NUM_LIST,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- Node kinds which are simple markers in the document.
subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH;
type Node_List_Ref is private;
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST =>
Level : Natural := 0;
Header : Wiki.Strings.WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : Wiki.Strings.WString (1 .. Len);
when N_LINK | N_IMAGE | N_QUOTE =>
Link_Attr : Wiki.Attributes.Attribute_List;
Title : Wiki.Strings.WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag;
Attributes : Wiki.Attributes.Attribute_List;
Children : Node_List_Access;
Parent : Node_Type_Access;
when N_PREFORMAT =>
Preformatted : Wiki.Strings.WString (1 .. Len);
when others =>
null;
end case;
end record;
-- Append a node to the document.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
-- Append a node to the node list.
procedure Append (Into : in out Node_List_Ref;
Node : in Node_Type_Access);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (List : in Node_List_Access;
Process : not null access procedure (Node : in Node_Type));
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (List : in Node_List_Ref;
Process : not null access procedure (Node : in Node_Type));
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited new Util.Refs.Ref_Entity with record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
-- Finalize the node list to release the allocated memory.
overriding
procedure Finalize (List : in out Node_List);
-- Append a node to the node list.
-- procedure Append (Into : in out Node_List;
-- Node : in Node_Type_Access);
package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access);
type Node_List_Ref is new Node_List_Refs.Ref with null record;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki -- Ada Wiki Engine
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Strings;
with Util.Refs;
package Wiki.Nodes is
pragma Preelaborate;
type Node_Kind is (N_LINE_BREAK,
N_HORIZONTAL_RULE,
N_PARAGRAPH,
N_HEADER,
N_BLOCKQUOTE,
N_QUOTE,
N_TAG_START,
N_PREFORMAT,
N_LIST,
N_NUM_LIST,
N_INDENT,
N_TEXT,
N_LINK,
N_IMAGE);
-- Node kinds which are simple markers in the document.
subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_PARAGRAPH;
type Node_List_Ref is private;
type Node_List is limited private;
type Node_List_Access is access all Node_List;
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Node_Kind; Len : Natural) is limited record
case Kind is
when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST =>
Level : Natural := 0;
Header : Wiki.Strings.WString (1 .. Len);
when N_TEXT =>
Format : Format_Map;
Text : Wiki.Strings.WString (1 .. Len);
when N_LINK | N_IMAGE | N_QUOTE =>
Link_Attr : Wiki.Attributes.Attribute_List;
Title : Wiki.Strings.WString (1 .. Len);
when N_TAG_START =>
Tag_Start : Html_Tag;
Attributes : Wiki.Attributes.Attribute_List;
Children : Node_List_Access;
Parent : Node_Type_Access;
when N_PREFORMAT =>
Preformatted : Wiki.Strings.WString (1 .. Len);
when others =>
null;
end case;
end record;
-- Append a node to the tag node.
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access);
-- Append a node to the document.
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access);
-- Append a node to the node list.
procedure Append (Into : in out Node_List_Ref;
Node : in Node_Type_Access);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (List : in Node_List_Access;
Process : not null access procedure (Node : in Node_Type));
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (List : in Node_List_Ref;
Process : not null access procedure (Node : in Node_Type));
private
NODE_LIST_BLOCK_SIZE : constant Positive := 20;
type Node_Array is array (Positive range <>) of Node_Type_Access;
type Node_List_Block;
type Node_List_Block_Access is access all Node_List_Block;
type Node_List_Block (Max : Positive) is limited record
Next : Node_List_Block_Access;
Last : Natural := 0;
List : Node_Array (1 .. Max);
end record;
type Node_List is limited new Util.Refs.Ref_Entity with record
Current : Node_List_Block_Access;
Length : Natural := 0;
First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE);
end record;
-- Finalize the node list to release the allocated memory.
overriding
procedure Finalize (List : in out Node_List);
-- Append a node to the node list.
-- procedure Append (Into : in out Node_List;
-- Node : in Node_Type_Access);
package Node_List_Refs is new Util.Refs.References (Node_List, Node_List_Access);
type Node_List_Ref is new Node_List_Refs.Ref with null record;
end Wiki.Nodes;
|
Declare the Append procedure
|
Declare the Append procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
25d038d6f41805a62a596ac50dd9596a36436334
|
regtests/security-oauth-servers-tests.adb
|
regtests/security-oauth-servers-tests.adb
|
-----------------------------------------------------------------------
-- Security-oauth-servers-tests - Unit tests for server side OAuth
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Auth.Tests;
with Security.OAuth.File_Registry;
package body Security.OAuth.Servers.Tests is
use Auth.Tests;
use File_Registry;
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application",
Test_Application_Manager'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify",
Test_User_Verify'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token",
Test_Token_Password'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Authenticate",
Test_Bad_Token'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.File_Registry.Load",
Test_Load_Registry'Access);
end Add_Tests;
-- ------------------------------
-- Test the application manager.
-- ------------------------------
procedure Test_Application_Manager (T : in out Test) is
Manager : File_Application_Manager;
App : Application;
begin
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Manager.Add_Application (App);
-- Check that we can find our application.
declare
A : constant Application'Class := Manager.Find_Application ("my-app-id");
begin
Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier,
"Invalid application returned by Find");
end;
-- Check that an exception is raised for an invalid client ID.
begin
declare
A : constant Application'Class := Manager.Find_Application ("unkown-app-id");
begin
Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier);
end;
exception
when Invalid_Application =>
null;
end;
end Test_Application_Manager;
-- ------------------------------
-- Test the user registration and verification.
-- ------------------------------
procedure Test_User_Verify (T : in out Test) is
Manager : File_Realm_Manager;
Auth : Principal_Access;
begin
Manager.Add_User ("Gandalf", "Mithrandir");
Manager.Verify ("Gandalf", "mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid password");
Manager.Verify ("Sauron", "Mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid user");
Manager.Verify ("Gandalf", "Mithrandir", Auth);
T.Assert (Auth /= null, "Verify password operation failed for a good user/password");
end Test_User_Verify;
-- ------------------------------
-- Test the token operation that produces an access token from user/password.
-- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant
-- ------------------------------
procedure Test_Token_Password (T : in out Test) is
use type Util.Strings.Name_Access;
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
App : Application;
Grant : Grant_Type;
Auth_Grant : Grant_Type;
Params : Test_Parameters;
begin
-- Add one test application.
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Apps.Add_Application (App);
-- Add one test user.
Realm.Add_User ("Gandalf", "Mithrandir");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Set_Private_Key ("server-private-key-no-so-secure");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the user/password is missing");
Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the password is missing");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the password is invalid");
Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the client_secret is invalid");
Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "my-secret");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
T.Assert (Grant.Error = null, "Expecting null error");
T.Assert (Length (Grant.Token) > 20,
"Expecting a token with some reasonable size");
T.Assert (Grant.Auth /= null,
"Expecting a non null auth principal");
Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name,
"Invalid user name in the principal");
-- Verify the access token.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant,
"Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal");
end loop;
-- Verify the modified access token.
Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for the authenticate");
Manager.Revoke (To_String (Grant.Token));
-- Verify the access is now denied.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Revoked_Grant,
"Expecting Revoked_Grant for the authenticate");
end loop;
-- Change application token expiration time to 1 second.
App.Expire_Timeout := 1.0;
Apps.Add_Application (App);
-- Make the access token.
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
-- Verify the access token.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant,
"Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null,
"Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth,
"Expecting valid auth principal");
end loop;
-- Wait for the token to expire.
delay 2.0;
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Expired_Grant,
"Expecting Expired when the access token is checked");
end loop;
end Test_Token_Password;
-- ------------------------------
-- Test the access token validation with invalid tokens (bad formed).
-- ------------------------------
procedure Test_Bad_Token (T : in out Test) is
Manager : Auth_Manager;
Auth_Grant : Grant_Type;
begin
Manager.Authenticate ("x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate (".", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("..", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("a..", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("..b", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("a..b", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
end Test_Bad_Token;
-- ------------------------------
-- Test the loading configuration files for the File_Registry.
-- ------------------------------
procedure Test_Load_Registry (T : in out Test) is
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
Grant : Grant_Type;
Auth_Grant : Grant_Type;
Params : Test_Parameters;
begin
Apps.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "apps");
Realm.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "users");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Set_Private_Key ("server-private-key-no-so-secure");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "app-id-1");
Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "app-secret-1");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Params.Set_Parameter (Security.OAuth.USERNAME, "joe");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
end Test_Load_Registry;
end Security.OAuth.Servers.Tests;
|
-----------------------------------------------------------------------
-- security-oauth-servers-tests - Unit tests for server side OAuth
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Security.Auth.Tests;
with Security.OAuth.File_Registry;
package body Security.OAuth.Servers.Tests is
use Auth.Tests;
use File_Registry;
package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application",
Test_Application_Manager'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify",
Test_User_Verify'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token",
Test_Token_Password'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Authenticate",
Test_Bad_Token'Access);
Caller.Add_Test (Suite, "Test Security.OAuth.File_Registry.Load",
Test_Load_Registry'Access);
end Add_Tests;
-- ------------------------------
-- Test the application manager.
-- ------------------------------
procedure Test_Application_Manager (T : in out Test) is
Manager : File_Application_Manager;
App : Application;
begin
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Manager.Add_Application (App);
-- Check that we can find our application.
declare
A : constant Application'Class := Manager.Find_Application ("my-app-id");
begin
Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier,
"Invalid application returned by Find");
end;
-- Check that an exception is raised for an invalid client ID.
begin
declare
A : constant Application'Class := Manager.Find_Application ("unkown-app-id");
begin
Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier);
end;
exception
when Invalid_Application =>
null;
end;
end Test_Application_Manager;
-- ------------------------------
-- Test the user registration and verification.
-- ------------------------------
procedure Test_User_Verify (T : in out Test) is
Manager : File_Realm_Manager;
Auth : Principal_Access;
begin
Manager.Add_User ("Gandalf", "Mithrandir");
Manager.Verify ("Gandalf", "mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid password");
Manager.Verify ("Sauron", "Mithrandir", Auth);
T.Assert (Auth = null, "Verify password should fail with an invalid user");
Manager.Verify ("Gandalf", "Mithrandir", Auth);
T.Assert (Auth /= null, "Verify password operation failed for a good user/password");
end Test_User_Verify;
-- ------------------------------
-- Test the token operation that produces an access token from user/password.
-- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant
-- ------------------------------
procedure Test_Token_Password (T : in out Test) is
use type Util.Strings.Name_Access;
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
App : Application;
Grant : Grant_Type;
Auth_Grant : Grant_Type;
Params : Test_Parameters;
begin
-- Add one test application.
App.Set_Application_Identifier ("my-app-id");
App.Set_Application_Secret ("my-secret");
App.Set_Application_Callback ("my-callback");
Apps.Add_Application (App);
-- Add one test user.
Realm.Add_User ("Gandalf", "Mithrandir");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Set_Private_Key ("server-private-key-no-so-secure");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "");
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when client_id is empty");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the user/password is missing");
Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the password is missing");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the password is invalid");
Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant when the client_secret is invalid");
Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "my-secret");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
T.Assert (Grant.Error = null, "Expecting null error");
T.Assert (Length (Grant.Token) > 20,
"Expecting a token with some reasonable size");
T.Assert (Grant.Auth /= null,
"Expecting a non null auth principal");
Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name,
"Invalid user name in the principal");
-- Verify the access token.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant,
"Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal");
end loop;
-- Verify the modified access token.
Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for the authenticate");
Manager.Revoke (To_String (Grant.Token));
-- Verify the access is now denied.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Revoked_Grant,
"Expecting Revoked_Grant for the authenticate");
end loop;
-- Change application token expiration time to 1 second.
App.Expire_Timeout := 1.0;
Apps.Add_Application (App);
-- Make the access token.
Manager.Token (Params, Grant);
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
-- Verify the access token.
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Request = Access_Grant,
"Expecting Access_Grant for the authenticate");
T.Assert (Auth_Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the access token is checked");
T.Assert (Auth_Grant.Error = null,
"Expecting null error for access_token");
T.Assert (Auth_Grant.Auth = Grant.Auth,
"Expecting valid auth principal");
end loop;
-- Wait for the token to expire.
delay 2.0;
for I in 1 .. 5 loop
Manager.Authenticate (To_String (Grant.Token), Auth_Grant);
T.Assert (Auth_Grant.Status = Expired_Grant,
"Expecting Expired when the access token is checked");
end loop;
end Test_Token_Password;
-- ------------------------------
-- Test the access token validation with invalid tokens (bad formed).
-- ------------------------------
procedure Test_Bad_Token (T : in out Test) is
Manager : Auth_Manager;
Auth_Grant : Grant_Type;
begin
Manager.Authenticate ("x", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate (".", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("..", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("a..", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("..b", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
Manager.Authenticate ("a..b", Auth_Grant);
T.Assert (Auth_Grant.Status = Invalid_Grant,
"Expecting Invalid_Grant for badly formed token");
end Test_Bad_Token;
-- ------------------------------
-- Test the loading configuration files for the File_Registry.
-- ------------------------------
procedure Test_Load_Registry (T : in out Test) is
Apps : aliased File_Application_Manager;
Realm : aliased File_Realm_Manager;
Manager : Auth_Manager;
Grant : Grant_Type;
Params : Test_Parameters;
begin
Apps.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "apps");
Realm.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "users");
-- Configure the auth manager.
Manager.Set_Application_Manager (Apps'Unchecked_Access);
Manager.Set_Realm_Manager (Realm'Unchecked_Access);
Manager.Set_Private_Key ("server-private-key-no-so-secure");
Params.Set_Parameter (Security.OAuth.CLIENT_ID, "app-id-1");
Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "app-secret-1");
Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password");
Params.Set_Parameter (Security.OAuth.USERNAME, "joe");
Params.Set_Parameter (Security.OAuth.PASSWORD, "test");
Manager.Token (Params, Grant);
T.Assert (Grant.Request = Password_Grant,
"Expecting Password_Grant for the grant request");
T.Assert (Grant.Status = Valid_Grant,
"Expecting Valid_Grant when the user/password are correct");
end Test_Load_Registry;
end Security.OAuth.Servers.Tests;
|
Remove unused variable
|
Remove unused variable
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
67bf0362a8c0d73b7cd840f420f72a4494b4c85b
|
src/security-oauth.ads
|
src/security-oauth.ads
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == OAuth ==
-- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization
-- framework as defined by the IETF working group.
-- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26
package Security.OAuth is
-- OAuth 2.0: Section 10.2.2. Initial Registry Contents
-- RFC 6749: 11.2.2. Initial Registry Contents
CLIENT_ID : constant String := "client_id";
CLIENT_SECRET : constant String := "client_secret";
RESPONSE_TYPE : constant String := "response_type";
REDIRECT_URI : constant String := "redirect_uri";
SCOPE : constant String := "scope";
STATE : constant String := "state";
CODE : constant String := "code";
ERROR_DESCRIPTION : constant String := "error_description";
ERROR_URI : constant String := "error_uri";
GRANT_TYPE : constant String := "grant_type";
ACCESS_TOKEN : constant String := "access_token";
TOKEN_TYPE : constant String := "token_type";
EXPIRES_IN : constant String := "expires_in";
USERNAME : constant String := "username";
PASSWORD : constant String := "password";
REFRESH_TOKEN : constant String := "refresh_token";
-- RFC 6749: 5.2. Error Response
INVALID_REQUEST : aliased constant String := "invalid_request";
INVALID_CLIENT : aliased constant String := "invalid_client";
INVALID_GRANT : aliased constant String := "invalid_grant";
UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client";
UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type";
INVALID_SCOPE : aliased constant String := "invalid_scope";
-- RFC 6749: 4.1.2.1. Error Response
ACCESS_DENIED : aliased constant String := "access_denied";
UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type";
SERVER_ERROR : aliased constant String := "server_error";
TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable";
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is tagged private;
private
type Application is tagged record
Client_Id : Ada.Strings.Unbounded.Unbounded_String;
Secret : Ada.Strings.Unbounded.Unbounded_String;
Callback : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == OAuth ==
-- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization
-- framework as defined by the IETF working group.
-- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26
package Security.OAuth is
-- OAuth 2.0: Section 10.2.2. Initial Registry Contents
-- RFC 6749: 11.2.2. Initial Registry Contents
CLIENT_ID : constant String := "client_id";
CLIENT_SECRET : constant String := "client_secret";
RESPONSE_TYPE : constant String := "response_type";
REDIRECT_URI : constant String := "redirect_uri";
SCOPE : constant String := "scope";
STATE : constant String := "state";
CODE : constant String := "code";
ERROR_DESCRIPTION : constant String := "error_description";
ERROR_URI : constant String := "error_uri";
GRANT_TYPE : constant String := "grant_type";
ACCESS_TOKEN : constant String := "access_token";
TOKEN_TYPE : constant String := "token_type";
EXPIRES_IN : constant String := "expires_in";
USERNAME : constant String := "username";
PASSWORD : constant String := "password";
REFRESH_TOKEN : constant String := "refresh_token";
-- RFC 6749: 5.2. Error Response
INVALID_REQUEST : aliased constant String := "invalid_request";
INVALID_CLIENT : aliased constant String := "invalid_client";
INVALID_GRANT : aliased constant String := "invalid_grant";
UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client";
UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type";
INVALID_SCOPE : aliased constant String := "invalid_scope";
-- RFC 6749: 4.1.2.1. Error Response
ACCESS_DENIED : aliased constant String := "access_denied";
UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type";
SERVER_ERROR : aliased constant String := "server_error";
TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable";
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is tagged private;
-- Get the application identifier.
function Get_Application_Identifier (App : in Application) return String;
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
procedure Set_Application_Identifier (App : in out Application;
Client : in String);
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
procedure Set_Application_Secret (App : in out Application;
Secret : in String);
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
procedure Set_Application_Callback (App : in out Application;
URI : in String);
private
type Application is tagged record
Client_Id : Ada.Strings.Unbounded.Unbounded_String;
Secret : Ada.Strings.Unbounded.Unbounded_String;
Callback : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth;
|
Declare Get_Application_Identifier, Set_Application_Identifier, Set_Application_Secret and Set_Application_Callback
|
Declare Get_Application_Identifier, Set_Application_Identifier, Set_Application_Secret
and Set_Application_Callback
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
ffe12dc7f93b9c041a9fdd5a3ec0821e566cd40c
|
awa/plugins/awa-storages/src/awa-storages.ads
|
awa/plugins/awa-storages/src/awa-storages.ads
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Storages</b> module provides a set of storage services allowing an application
-- to store data files, documents, images in a persistent area. The persistent store can
-- be on a file system, in the database or provided by a remote service such as
-- Amazon Simple Storage Service.
--
-- == Creating a storage ==
-- A content in the storage is represented by a `Storage_Ref` instance. The data itself
-- can be physically stored in the file system (`FILE` mode), in the database (`DATABASE`
-- mode) or on a remote server (`URL` mode). To put a file in the storage, first create
-- the storage object instance:
--
-- Data : AWA.Storages.Models.Storage_Ref;
--
-- Then setup the storage mode that you want. The storage service uses this information
-- to save the data in a file, in the database or in a remote service (in the future).
--
-- Data.Set_Storage (Storage => AWA.Storages.Models.DATABASE);
--
-- To save a file in the store, we can use the `Save` operation. It will read the file
-- and put in in the corresponding persistent store (the database in this example).
--
-- Service.Save (Into => Data, Path => Path_To_The_File);
--
-- Upon successful completion, the storage instance `Data` will be allocated a unique
-- identifier that can be retrieved by `Get_Id` or `Get_Key`.
--
-- == Getting the data ==
-- Several operations are defined to retrieve the data. Each of them has been designed
-- to optimize the retrieval and
--
-- * The data can be retrieved in a local file.
-- This mode is useful if an external program must be launched and be able to read
-- the file. If the storage mode of the data is `FILE`, the path of the file on
-- the storage file system is used. For other storage modes, the file is saved
-- in a temporary file. In that case the `Store_Local` database table is used
-- to track such locally saved data.
--
-- * The data can be returned as a stream.
-- When the application has to read the data, opening a read stream connection is
-- the most efficient mechanism.
--
-- === Local file ===
-- To access the data by using a local file, we must define a local storage reference:
--
-- Data : AWA.Storages.Models.Store_Local_Ref;
--
-- and use the `Load` operation with the storage identifier. When loading locally we
-- also indicate whether the file will be read or written. A file that is in `READ` mode
-- can be shared by several tasks or processes. A file that is in `WRITE` mode will have
-- a specific copy for the caller. An optional expiration parameter indicate when the
-- local file representation can expire.
--
-- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY);
--
-- Once the load operation succeeded, the data is stored on the file system and
-- the local path is obtained by using the `Get_Path` operation:
--
-- Path : constant String := Data.Get_Path;
--
-- == Ada Beans ==
-- @include storages.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png]
--
-- @include Storages.hbm.xml
package AWA.Storages is
end AWA.Storages;
|
-----------------------------------------------------------------------
-- awa-storages -- Storage module
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <b>Storages</b> module provides a set of storage services allowing an application
-- to store data files, documents, images in a persistent area. The persistent store can
-- be on a file system, in the database or provided by a remote service such as
-- Amazon Simple Storage Service.
--
-- == Creating a storage ==
-- A data in the storage is represented by a `Storage_Ref` instance. The data itself
-- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE`
-- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create
-- the storage object instance:
--
-- Data : AWA.Storages.Models.Storage_Ref;
--
-- Then setup the storage mode that you want. The storage service uses this information
-- to save the data in a file, in the database or in a remote service (in the future).
--
-- Data.Set_Storage (Storage => AWA.Storages.Models.DATABASE);
--
-- To save a file in the store, we can use the `Save` operation of the storage service.
-- It will read the file and put in in the corresponding persistent store (the database
-- in this example).
--
-- Service.Save (Into => Data, Path => Path_To_The_File);
--
-- Upon successful completion, the storage instance `Data` will be allocated a unique
-- identifier that can be retrieved by `Get_Id` or `Get_Key`.
--
-- == Getting the data ==
-- Several operations are defined to retrieve the data. Each of them has been designed
-- to optimize the retrieval and
--
-- * The data can be retrieved in a local file.
-- This mode is useful if an external program must be launched and be able to read
-- the file. If the storage mode of the data is `FILE`, the path of the file on
-- the storage file system is used. For other storage modes, the file is saved
-- in a temporary file. In that case the `Store_Local` database table is used
-- to track such locally saved data.
--
-- * The data can be returned as a stream.
-- When the application has to read the data, opening a read stream connection is
-- the most efficient mechanism.
--
-- === Local file ===
-- To access the data by using a local file, we must define a local storage reference:
--
-- Data : AWA.Storages.Models.Store_Local_Ref;
--
-- and use the `Load` operation with the storage identifier. When loading locally we
-- also indicate whether the file will be read or written. A file that is in `READ` mode
-- can be shared by several tasks or processes. A file that is in `WRITE` mode will have
-- a specific copy for the caller. An optional expiration parameter indicate when the
-- local file representation can expire.
--
-- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY);
--
-- Once the load operation succeeded, the data is stored on the file system and
-- the local path is obtained by using the `Get_Path` operation:
--
-- Path : constant String := Data.Get_Path;
--
-- == Ada Beans ==
-- @include storages.xml
--
-- == Model ==
-- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png]
--
-- @include Storages.hbm.xml
package AWA.Storages is
end AWA.Storages;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
500faca423d3299fa764cba784d34190074a13f7
|
matp/src/symbols/mat-symbols-targets.ads
|
matp/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Bfd.Constants;
with Util.Refs;
with MAT.Types;
with MAT.Consoles;
with MAT.Memory;
package MAT.Symbols.Targets is
-- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or
-- a shared library loaded by the program. The <tt>Region</tt> indicates
-- the text segment address of the program or the loaded library.
type Region_Symbols is new Util.Refs.Ref_Entity with record
Region : MAT.Memory.Region_Info;
Offset : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Region_Symbols_Access is access all Region_Symbols;
-- Load the symbol table for the associated region.
procedure Open (Symbols : in out Region_Symbols;
Path : in String;
Search_Path : in String);
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
type Symbol_Info is limited record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
Symbols : Region_Symbols_Ref;
end record;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Region_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
Path : Ada.Strings.Unbounded.Unbounded_String;
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr);
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map);
-- Demangle the symbol.
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
-- Find the symbol in the symbol table and return the start and end address.
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Name : in String;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015, 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.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Bfd.Constants;
with Util.Refs;
with MAT.Types;
with MAT.Consoles;
with MAT.Memory;
package MAT.Symbols.Targets is
-- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or
-- a shared library loaded by the program. The <tt>Region</tt> indicates
-- the text segment address of the program or the loaded library.
type Region_Symbols is new Util.Refs.Ref_Entity with record
Region : MAT.Memory.Region_Info;
Offset : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Region_Symbols_Access is access all Region_Symbols;
-- Load the symbol table for the associated region.
procedure Open (Symbols : in out Region_Symbols;
Path : in String;
Search_Path : in String);
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
type Symbol_Info is limited record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
Symbols : Region_Symbols_Ref;
end record;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Region_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
Path : Ada.Strings.Unbounded.Unbounded_String;
Search_Path : Ada.Strings.Unbounded.Unbounded_String;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr);
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map);
-- Demangle the symbol.
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
-- Find the symbol in the symbol table and return the start and end address.
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Name : in String;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr);
-- Find the symbol region in the symbol table which contains the given address
-- and return the start and end address.
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Addr : in Mat.Types.Target_Addr;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
Declare the Find_Symbol_Range procedure to find a function address range known some code address
|
Declare the Find_Symbol_Range procedure to find a function address range known some code address
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
0b9eb910f740896cdc428965bd75a262e42f01fa
|
src/gen-commands-database.adb
|
src/gen-commands-database.adb
|
-----------------------------------------------------------------------
-- gen-commands-database -- Database creation from application model
-- Copyright (C) 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.Text_IO;
with Ada.Strings.Fixed;
with Ada.Directories;
with Ada.Exceptions;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Vectors;
with ADO.Drivers;
with ADO.Sessions.Sources;
with ADO.Schemas.Databases;
package body Gen.Commands.Database is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Database");
function Get_Schema_Path (Model_Dir : in String;
Model : in String;
Config : in ADO.Sessions.Sources.Data_Source) return String;
function Get_Schema_Path (Model_Dir : in String;
Model : in String;
Config : in ADO.Sessions.Sources.Data_Source) return String is
Driver : constant String := Config.Get_Driver;
Dir : constant String := Util.Files.Compose (Model_Dir, Driver);
begin
return Util.Files.Compose (Dir, "create-" & Model & "-" & Driver & ".sql");
end Get_Schema_Path;
-- ------------------------------
-- 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
pragma Unreferenced (Cmd, Name);
procedure Create_Database (Model_Dir : in String;
Database : in String;
Username : in String;
Password : in String);
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_Database (Model_Dir : in String;
Database : in String;
Username : in String;
Password : in String) is
Admin : ADO.Sessions.Sources.Data_Source;
Config : ADO.Sessions.Sources.Data_Source;
Messages : Util.Strings.Vectors.Vector;
begin
Config.Set_Connection (Database);
Admin := Config;
if Config.Get_Database = "" then
Generator.Error ("Invalid database connection: no database name specified");
return;
end if;
declare
Name : constant String := Generator.Get_Project_Name;
Path : constant String := Get_Schema_Path (Model_Dir, Name, Config);
begin
Log.Info ("Creating database tables using schema '{0}'", Path);
if not Ada.Directories.Exists (Path) then
Generator.Error ("SQL file '{0}' does not exist.", Path);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
if Config.Get_Driver = "mysql" or Config.Get_Driver = "postgresql" then
if Config.Get_Property ("user") = "" then
Generator.Error ("Invalid database connection: missing user property");
return;
end if;
Admin.Set_Property ("user", Username);
Admin.Set_Property ("password", Password);
elsif Config.Get_Driver /= "sqlite" then
Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver);
return;
end if;
Admin.Set_Database ("");
ADO.Schemas.Databases.Create_Database (Admin, Config, Path, Messages);
-- Report the messages
for Msg of Messages loop
Log.Error ("{0}", Msg);
end loop;
end;
-- 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 out 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, 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.Text_IO;
with Ada.Strings.Fixed;
with Ada.Directories;
with Ada.Exceptions;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Util.Strings.Vectors;
with ADO.Drivers;
with ADO.Sessions.Sources;
with ADO.Schemas.Databases;
package body Gen.Commands.Database is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Database");
function Get_Schema_Path (Model_Dir : in String;
Model : in String;
Config : in ADO.Sessions.Sources.Data_Source) return String;
function Get_Schema_Path (Model_Dir : in String;
Model : in String;
Config : in ADO.Sessions.Sources.Data_Source) return String is
Driver : constant String := Config.Get_Driver;
Dir : constant String := Util.Files.Compose (Model_Dir, Driver);
begin
return Util.Files.Compose (Dir, "create-" & Model & "-" & Driver & ".sql");
end Get_Schema_Path;
-- ------------------------------
-- 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
pragma Unreferenced (Cmd, Name);
procedure Create_Database (Model_Dir : in String;
Database : in String;
Username : in String;
Password : in String);
-- ------------------------------
-- Create the database, the user and the tables.
-- ------------------------------
procedure Create_Database (Model_Dir : in String;
Database : in String;
Username : in String;
Password : in String) is
Admin : ADO.Sessions.Sources.Data_Source;
Config : ADO.Sessions.Sources.Data_Source;
Messages : Util.Strings.Vectors.Vector;
begin
Config.Set_Connection (Database);
Admin := Config;
if Config.Get_Database = "" then
Generator.Error ("Invalid database connection: no database name specified");
return;
end if;
declare
Name : constant String := Generator.Get_Project_Name;
Path : constant String := Get_Schema_Path (Model_Dir, Name, Config);
begin
Log.Info ("Creating database tables using schema '{0}'", Path);
if not Ada.Directories.Exists (Path) then
Generator.Error ("SQL file '{0}' does not exist.", Path);
Generator.Error ("Please, run the following command: dynamo generate db");
return;
end if;
if Config.Get_Driver = "mysql" or Config.Get_Driver = "postgresql" then
if Config.Get_Property ("user") = "" then
Generator.Error ("Invalid database connection: missing user property");
return;
end if;
Admin.Set_Property ("user", Username);
Admin.Set_Property ("password", Password);
elsif Config.Get_Driver /= "sqlite" then
Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver);
return;
end if;
Admin.Set_Database ("");
ADO.Schemas.Databases.Create_Database (Admin, Config, Path, Messages);
-- Report the messages
for Msg of Messages loop
Log.Error ("{0}", Msg);
end loop;
end;
-- 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 out Command;
Name : in String;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, 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;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
f4dfdeecf2aab3fac712219764c2e1339262fb89
|
awa/src/awa-permissions-services.adb
|
awa/src/awa-permissions-services.adb
|
-----------------------------------------------------------------------
-- awa-permissions-services -- Permissions controller
-- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions.Entities;
with ADO.Statements;
with Util.Log.Loggers;
with Security.Policies.URLs;
with AWA.Permissions.Models;
with AWA.Services.Contexts;
package body AWA.Permissions.Services is
use ADO.Sessions;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions.Services");
-- ------------------------------
-- Check if the permission with the name <tt>Name</tt> is granted for the current user.
-- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified.
-- Returns True if the user is granted the given permission.
-- ------------------------------
function Has_Permission (Name : in Util.Beans.Objects.Object;
Entity : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
use type Security.Contexts.Security_Context_Access;
Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current;
Perm : constant String := Util.Beans.Objects.To_String (Name);
Result : Boolean;
begin
if Util.Beans.Objects.Is_Empty (Name) or Context = null then
Result := False;
elsif Util.Beans.Objects.Is_Empty (Entity) then
Result := Context.Has_Permission (Perm);
else
declare
P : Entity_Permission (Security.Permissions.Get_Permission_Index (Perm));
begin
P.Entity := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Entity));
Result := Context.Has_Permission (P);
end;
end if;
return Util.Beans.Objects.To_Object (Result);
exception
when Security.Permissions.Invalid_Name =>
Log.Error ("Invalid permission {0}", Perm);
raise;
end Has_Permission;
URI : aliased constant String := "http://code.google.com/p/ada-awa/auth";
-- ------------------------------
-- Register the security EL functions in the EL mapper.
-- ------------------------------
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "hasPermission",
Namespace => URI,
Func => Has_Permission'Access,
Optimize => False);
end Set_Functions;
-- ------------------------------
-- Get the permission manager associated with the security context.
-- Returns null if there is none.
-- ------------------------------
function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class)
return Permission_Manager_Access is
use type Security.Policies.Policy_Manager_Access;
M : constant Security.Policies.Policy_Manager_Access
:= Context.Get_Permission_Manager;
begin
if M = null then
Log.Info ("There is no permission manager");
return null;
elsif not (M.all in Permission_Manager'Class) then
Log.Info ("Permission manager is not a AWA permission manager");
return null;
else
return Permission_Manager'Class (M.all)'Access;
end if;
end Get_Permission_Manager;
-- ------------------------------
-- Get the application instance.
-- ------------------------------
function Get_Application (Manager : in Permission_Manager)
return AWA.Applications.Application_Access is
begin
return Manager.App;
end Get_Application;
-- ------------------------------
-- Set the application instance.
-- ------------------------------
procedure Set_Application (Manager : in out Permission_Manager;
App : in AWA.Applications.Application_Access) is
begin
Manager.App := App;
end Set_Application;
-- ------------------------------
-- Add a permission for the current user to access the entity identified by
-- <b>Entity</b> and <b>Kind</b>.
-- ------------------------------
procedure Add_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Workspace : in ADO.Identifier;
Permission : in Permission_Type) is
pragma Unreferenced (Manager);
Ctx : constant AWA.Services.Contexts.Service_Context_Access
:= AWA.Services.Contexts.Current;
DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Perm : AWA.Permissions.Models.ACL_Ref;
begin
Log.Info ("Adding permission");
Ctx.Start;
Perm.Set_Entity_Type (Kind);
Perm.Set_User_Id (Ctx.Get_User_Identifier);
Perm.Set_Entity_Id (Entity);
Perm.Set_Writeable (Permission = AWA.Permissions.WRITE);
Perm.Set_Workspace_Id (Workspace);
Perm.Save (DB);
Ctx.Commit;
end Add_Permission;
-- ------------------------------
-- Check that the current user has the specified permission.
-- Raise NO_PERMISSION exception if the user does not have the permission.
-- ------------------------------
procedure Check_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type) is
pragma Unreferenced (Manager, Permission);
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission);
Query.Bind_Param ("user_id", User);
Query.Bind_Param ("entity_id", Entity);
Query.Bind_Param ("entity_type", Integer (Kind));
declare
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query);
begin
Stmt.Execute;
if not Stmt.Has_Elements then
Log.Info ("User {0} does not have permission to access entity {1}/{2}",
ADO.Identifier'Image (User), ADO.Identifier'Image (Entity),
ADO.Entity_Type'Image (Kind));
raise NO_PERMISSION;
end if;
end;
end Check_Permission;
-- ------------------------------
-- Get the role names that grant the given permission.
-- ------------------------------
function Get_Role_Names (Manager : in Permission_Manager;
Permission : in Security.Permissions.Permission_Index)
return Security.Policies.Roles.Role_Name_Array is
begin
return Manager.Roles.Get_Role_Names (Manager.Roles.Get_Grants (Permission));
end Get_Role_Names;
-- ------------------------------
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b> which is of type <b>Kind</b>.
-- ------------------------------
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Workspace : in ADO.Identifier;
Permission : in Permission_Type := READ) is
Acl : AWA.Permissions.Models.ACL_Ref;
begin
Acl.Set_User_Id (User);
Acl.Set_Entity_Type (Kind);
Acl.Set_Entity_Id (Entity);
Acl.Set_Writeable (Permission = WRITE);
Acl.Set_Workspace_Id (Workspace);
Acl.Save (Session);
Log.Info ("Permission created for {0} to access {1}, entity type {2}",
ADO.Identifier'Image (User),
ADO.Identifier'Image (Entity),
ADO.Entity_Type'Image (Kind));
end Add_Permission;
-- ------------------------------
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b>.
-- ------------------------------
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;
Permission : in Permission_Type := READ) is
Key : constant ADO.Objects.Object_Key := Entity.Get_Key;
Kind : constant ADO.Entity_Type
:= ADO.Sessions.Entities.Find_Entity_Type (Session => Session,
Object => Key);
begin
Add_Permission (Session, User, ADO.Objects.Get_Value (Key), Kind, Workspace, Permission);
end Add_Permission;
-- ------------------------------
-- Create a permission manager for the given application.
-- ------------------------------
function Create_Permission_Manager (App : in AWA.Applications.Application_Access)
return Security.Policies.Policy_Manager_Access is
Result : constant AWA.Permissions.Services.Permission_Manager_Access
:= new AWA.Permissions.Services.Permission_Manager (10);
RP : constant Security.Policies.Roles.Role_Policy_Access
:= new Security.Policies.Roles.Role_Policy;
RU : constant Security.Policies.URLs.URL_Policy_Access
:= new Security.Policies.URLs.URL_Policy;
RE : constant Entity_Policy_Access
:= new Entity_Policy;
begin
Result.Roles := RP;
Result.Add_Policy (RP.all'Access);
Result.Add_Policy (RU.all'Access);
Result.Add_Policy (RE.all'Access);
Result.Set_Application (App);
Log.Info ("Creation of the AWA Permissions manager");
return Result.all'Access;
end Create_Permission_Manager;
-- ------------------------------
-- Delete all the permissions for a user and on the given workspace.
-- ------------------------------
procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Workspace : in ADO.Identifier) is
Stmt : ADO.Statements.Delete_Statement
:= Session.Create_Statement (Models.ACL_TABLE);
Result : Natural;
begin
Stmt.Set_Filter (Filter => "workspace_id = ? AND user_id = ?");
Stmt.Add_Param (Value => Workspace);
Stmt.Add_Param (Value => User);
Stmt.Execute (Result);
Log.Info ("Deleted {0} permissions for user {1} in workspace {2}",
Natural'Image (Result), ADO.Identifier'Image (User),
ADO.Identifier'Image (Workspace));
end Delete_Permissions;
end AWA.Permissions.Services;
|
-----------------------------------------------------------------------
-- awa-permissions-services -- Permissions controller
-- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions.Entities;
with ADO.Statements;
with ADO.Caches.Discrete;
with Util.Log.Loggers;
with Util.Strings;
with Security.Policies.URLs;
with AWA.Permissions.Models;
with AWA.Services.Contexts;
package body AWA.Permissions.Services is
use ADO.Sessions;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions.Services");
package Permission_Cache is
new ADO.Caches.Discrete (Element_Type => Integer);
-- ------------------------------
-- Check if the permission with the name <tt>Name</tt> is granted for the current user.
-- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified.
-- Returns True if the user is granted the given permission.
-- ------------------------------
function Has_Permission (Name : in Util.Beans.Objects.Object;
Entity : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object is
use type Security.Contexts.Security_Context_Access;
Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current;
Perm : constant String := Util.Beans.Objects.To_String (Name);
Result : Boolean;
begin
if Util.Beans.Objects.Is_Empty (Name) or Context = null then
Result := False;
elsif Util.Beans.Objects.Is_Empty (Entity) then
Result := Context.Has_Permission (Perm);
else
declare
P : Entity_Permission (Security.Permissions.Get_Permission_Index (Perm));
begin
P.Entity := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Entity));
Result := Context.Has_Permission (P);
end;
end if;
return Util.Beans.Objects.To_Object (Result);
exception
when Security.Permissions.Invalid_Name =>
Log.Error ("Invalid permission {0}", Perm);
raise;
end Has_Permission;
URI : aliased constant String := "http://code.google.com/p/ada-awa/auth";
-- ------------------------------
-- Register the security EL functions in the EL mapper.
-- ------------------------------
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
begin
Mapper.Set_Function (Name => "hasPermission",
Namespace => URI,
Func => Has_Permission'Access,
Optimize => False);
end Set_Functions;
-- ------------------------------
-- Get the permission manager associated with the security context.
-- Returns null if there is none.
-- ------------------------------
function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class)
return Permission_Manager_Access is
use type Security.Policies.Policy_Manager_Access;
M : constant Security.Policies.Policy_Manager_Access
:= Context.Get_Permission_Manager;
begin
if M = null then
Log.Info ("There is no permission manager");
return null;
elsif not (M.all in Permission_Manager'Class) then
Log.Info ("Permission manager is not a AWA permission manager");
return null;
else
return Permission_Manager'Class (M.all)'Access;
end if;
end Get_Permission_Manager;
-- ------------------------------
-- Get the application instance.
-- ------------------------------
function Get_Application (Manager : in Permission_Manager)
return AWA.Applications.Application_Access is
begin
return Manager.App;
end Get_Application;
-- ------------------------------
-- Set the application instance.
-- ------------------------------
procedure Set_Application (Manager : in out Permission_Manager;
App : in AWA.Applications.Application_Access) is
begin
Manager.App := App;
end Set_Application;
-- ------------------------------
-- Initialize the permissions.
-- ------------------------------
procedure Start (Manager : in out Permission_Manager) is
package Perm renames Security.Permissions;
DB : ADO.Sessions.Master_Session := Manager.App.Get_Master_Session;
Cache : constant Permission_Cache.Cache_Type_Access := new Permission_Cache.Cache_Type;
Count : constant Perm.Permission_Index := Perm.Get_Last_Permission_Index;
Last : Natural := 0;
Insert : ADO.Statements.Insert_Statement;
Stmt : ADO.Statements.Query_Statement;
Load_Count : Natural := 0;
Add_Count : Natural := 0;
begin
Log.Info ("Initializing {0} permissions", Perm.Permission_Index'Image (Count));
DB.Begin_Transaction;
-- Step 1: load the permissions from the database.
Stmt := DB.Create_Statement ("SELECT id, name FROM awa_permission");
Stmt.Execute;
while Stmt.Has_Elements loop
declare
Id : constant Integer := Stmt.Get_Integer (0);
Name : constant String := Stmt.Get_String (1);
begin
Log.Debug ("Loaded permission {0} as {1}", Name, Util.Strings.Image (Id));
Permission_Cache.Insert (Cache.all, Name, Id);
Load_Count := Load_Count + 1;
if Id > Last then
Last := Id;
end if;
end;
Stmt.Next;
end loop;
-- Step 2: Check that every application permission is defined in the database.
-- Create the new entries and allocate them the last id.
for I in 1 .. Count loop
declare
Name : constant String := Perm.Get_Name (I);
Result : Integer;
begin
Result := Cache.Find (Name);
exception
when ADO.Caches.No_Value =>
Last := Last + 1;
Log.Info ("Adding permission {0} as {1}", Name, Util.Strings.Image (Last));
Insert := DB.Create_Statement (AWA.Permissions.Models.PERMISSION_TABLE);
Insert.Save_Field (Name => "id", Value => Last);
Insert.Save_Field (Name => "name", Value => Name);
Insert.Execute (Result);
Cache.Insert (Name, Last);
Add_Count := Add_Count + 1;
end;
end loop;
DB.Add_Cache ("permission", Cache.all'Access);
DB.Commit;
if Add_Count > 0 then
Log.Info ("Found {0} permissions in the database and created {1} permissions",
Util.Strings.Image (Load_Count), Util.Strings.Image (Add_Count));
else
Log.Info ("Found {0} permissions in the database",
Util.Strings.Image (Load_Count));
end if;
end Start;
-- ------------------------------
-- Add a permission for the current user to access the entity identified by
-- <b>Entity</b> and <b>Kind</b>.
-- ------------------------------
procedure Add_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Workspace : in ADO.Identifier;
Permission : in Permission_Type) is
pragma Unreferenced (Manager);
Ctx : constant AWA.Services.Contexts.Service_Context_Access
:= AWA.Services.Contexts.Current;
DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Perm : AWA.Permissions.Models.ACL_Ref;
begin
Log.Info ("Adding permission");
Ctx.Start;
Perm.Set_Entity_Type (Kind);
Perm.Set_User_Id (Ctx.Get_User_Identifier);
Perm.Set_Entity_Id (Entity);
Perm.Set_Writeable (Permission = AWA.Permissions.WRITE);
Perm.Set_Workspace_Id (Workspace);
Perm.Save (DB);
Ctx.Commit;
end Add_Permission;
-- ------------------------------
-- Check that the current user has the specified permission.
-- Raise NO_PERMISSION exception if the user does not have the permission.
-- ------------------------------
procedure Check_Permission (Manager : in Permission_Manager;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Permission : in Permission_Type) is
pragma Unreferenced (Manager, Permission);
use AWA.Services;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission);
Query.Bind_Param ("user_id", User);
Query.Bind_Param ("entity_id", Entity);
Query.Bind_Param ("entity_type", Integer (Kind));
declare
Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query);
begin
Stmt.Execute;
if not Stmt.Has_Elements then
Log.Info ("User {0} does not have permission to access entity {1}/{2}",
ADO.Identifier'Image (User), ADO.Identifier'Image (Entity),
ADO.Entity_Type'Image (Kind));
raise NO_PERMISSION;
end if;
end;
end Check_Permission;
-- ------------------------------
-- Get the role names that grant the given permission.
-- ------------------------------
function Get_Role_Names (Manager : in Permission_Manager;
Permission : in Security.Permissions.Permission_Index)
return Security.Policies.Roles.Role_Name_Array is
begin
return Manager.Roles.Get_Role_Names (Manager.Roles.Get_Grants (Permission));
end Get_Role_Names;
-- ------------------------------
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b> which is of type <b>Kind</b>.
-- ------------------------------
procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Entity : in ADO.Identifier;
Kind : in ADO.Entity_Type;
Workspace : in ADO.Identifier;
Permission : in Permission_Type := READ) is
Acl : AWA.Permissions.Models.ACL_Ref;
begin
Acl.Set_User_Id (User);
Acl.Set_Entity_Type (Kind);
Acl.Set_Entity_Id (Entity);
Acl.Set_Writeable (Permission = WRITE);
Acl.Set_Workspace_Id (Workspace);
Acl.Save (Session);
Log.Info ("Permission created for {0} to access {1}, entity type {2}",
ADO.Identifier'Image (User),
ADO.Identifier'Image (Entity),
ADO.Entity_Type'Image (Kind));
end Add_Permission;
-- ------------------------------
-- Add a permission for the user <b>User</b> to access the entity identified by
-- <b>Entity</b>.
-- ------------------------------
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;
Permission : in Permission_Type := READ) is
Key : constant ADO.Objects.Object_Key := Entity.Get_Key;
Kind : constant ADO.Entity_Type
:= ADO.Sessions.Entities.Find_Entity_Type (Session => Session,
Object => Key);
begin
Add_Permission (Session, User, ADO.Objects.Get_Value (Key), Kind, Workspace, Permission);
end Add_Permission;
-- ------------------------------
-- Create a permission manager for the given application.
-- ------------------------------
function Create_Permission_Manager (App : in AWA.Applications.Application_Access)
return Security.Policies.Policy_Manager_Access is
Result : constant AWA.Permissions.Services.Permission_Manager_Access
:= new AWA.Permissions.Services.Permission_Manager (10);
RP : constant Security.Policies.Roles.Role_Policy_Access
:= new Security.Policies.Roles.Role_Policy;
RU : constant Security.Policies.URLs.URL_Policy_Access
:= new Security.Policies.URLs.URL_Policy;
RE : constant Entity_Policy_Access
:= new Entity_Policy;
begin
Result.Roles := RP;
Result.Add_Policy (RP.all'Access);
Result.Add_Policy (RU.all'Access);
Result.Add_Policy (RE.all'Access);
Result.Set_Application (App);
Log.Info ("Creation of the AWA Permissions manager");
return Result.all'Access;
end Create_Permission_Manager;
-- ------------------------------
-- Delete all the permissions for a user and on the given workspace.
-- ------------------------------
procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session;
User : in ADO.Identifier;
Workspace : in ADO.Identifier) is
Stmt : ADO.Statements.Delete_Statement
:= Session.Create_Statement (Models.ACL_TABLE);
Result : Natural;
begin
Stmt.Set_Filter (Filter => "workspace_id = ? AND user_id = ?");
Stmt.Add_Param (Value => Workspace);
Stmt.Add_Param (Value => User);
Stmt.Execute (Result);
Log.Info ("Deleted {0} permissions for user {1} in workspace {2}",
Natural'Image (Result), ADO.Identifier'Image (User),
ADO.Identifier'Image (Workspace));
end Delete_Permissions;
end AWA.Permissions.Services;
|
Implement the Start procedure - load the permissions from the database and setup the permission cache - look each application permission and make sure we have an entry in the database - create a awa_permission row in the database for each new permission - register the permission cache to the database session manager
|
Implement the Start procedure
- load the permissions from the database and setup the permission cache
- look each application permission and make sure we have an entry in the database
- create a awa_permission row in the database for each new permission
- register the permission cache to the database session manager
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
687930ecbe7a8d015c57e3147e7c1f1bfb8bcf1a
|
src/gen-commands-distrib.adb
|
src/gen-commands-distrib.adb
|
-----------------------------------------------------------------------
-- gen-commands-distrib -- Distrib command for dynamo
-- Copyright (C) 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Ada.Text_IO;
package body Gen.Commands.Distrib 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);
begin
Generator.Read_Project ("dynamo.xml", True);
-- Setup the target directory where the distribution is created.
declare
Target_Dir : constant String := Get_Argument;
begin
if Target_Dir'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Target_Dir);
end;
-- Read the package description.
declare
Package_File : constant String := Get_Argument;
begin
if Package_File'Length > 0 then
Gen.Generator.Read_Package (Generator, Package_File);
else
Gen.Generator.Read_Package (Generator, "package.xml");
end if;
end;
-- Run the generation.
Gen.Generator.Prepare (Generator);
Gen.Generator.Generate_All (Generator);
Gen.Generator.Finish (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 ("dist: Build the distribution files to prepare the server installation");
Put_Line ("Usage: dist target-dir [package.xml]");
New_Line;
Put_Line (" The dist command reads the XML package description to build the"
& " distribution tree.");
Put_Line (" This command is intended to be used after the project is built. It prepares");
Put_Line (" the files for their installation on the target server in a "
& "production environment.");
Put_Line (" The package.xml describes what files are necessary on the server.");
Put_Line (" It allows to make transformations such as compressing Javascript, CSS and "
& "images");
end Help;
end Gen.Commands.Distrib;
|
-----------------------------------------------------------------------
-- gen-commands-distrib -- Distrib command for dynamo
-- Copyright (C) 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
package body Gen.Commands.Distrib is
-- ------------------------------
-- 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);
begin
if Args.Get_Count = 0 or Args.Get_Count > 2 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Read_Project ("dynamo.xml", True);
-- Setup the target directory where the distribution is created.
Generator.Set_Result_Directory (Args.Get_Argument (1));
-- Read the package description.
if Args.Get_Count = 2 then
Gen.Generator.Read_Package (Generator, Args.Get_Argument (2));
else
Gen.Generator.Read_Package (Generator, "package.xml");
end if;
-- Run the generation.
Gen.Generator.Prepare (Generator);
Gen.Generator.Generate_All (Generator);
Gen.Generator.Finish (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 ("dist: Build the distribution files to prepare the server installation");
Put_Line ("Usage: dist target-dir [package.xml]");
New_Line;
Put_Line (" The dist command reads the XML package description to build the"
& " distribution tree.");
Put_Line (" This command is intended to be used after the project is built. It prepares");
Put_Line (" the files for their installation on the target server in a "
& "production environment.");
Put_Line (" The package.xml describes what files are necessary on the server.");
Put_Line (" It allows to make transformations such as compressing Javascript, CSS and "
& "images");
end Help;
end Gen.Commands.Distrib;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
c0d22ee883664ed7b083291e198f23b6e5a36411
|
awa/plugins/awa-counters/regtests/awa-counters-modules-tests.adb
|
awa/plugins/awa-counters/regtests/awa-counters-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- 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.Measures;
with Util.Test_Caller;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Counters.Modules.Tests is
package User_Counter is
new AWA.Counters.Definition (AWA.Users.Models.USER_TABLE, "count");
package Session_Counter is
new AWA.Counters.Definition (AWA.Users.Models.SESSION_TABLE, "count");
package Caller is new Util.Test_Caller (Test, "Counters.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment",
Test_Increment'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Increment (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
AWA.Counters.Increment (User_Counter.Kind, Context.Get_User);
T.Manager := AWA.Counters.Modules.Get_Counter_Module;
T.Assert (T.Manager /= null, "There is no counter plugin");
T.Manager.Flush;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
AWA.Counters.Increment (User_Counter.Kind, Context.Get_User);
end loop;
Util.Measures.Report (S, "AWA.Counters.Increment", 1000);
end;
declare
S : Util.Measures.Stamp;
begin
T.Manager.Flush;
Util.Measures.Report (S, "AWA.Counters.Flush");
end;
-- T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
-- T.Assert (T.Manager /= null, "There is no wiki manager");
--
-- W.Set_Name ("Test wiki space");
-- T.Manager.Create_Wiki_Space (W);
-- T.Assert (W.Is_Inserted, "The new wiki space was not created");
--
-- W.Set_Name ("Test wiki space update");
-- W.Set_Is_Public (True);
-- T.Manager.Save_Wiki_Space (W);
--
-- T.Manager.Load_Wiki_Space (Wiki => W2,
-- Id => W.Get_Id);
-- Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
-- "Invalid wiki space name");
end Test_Increment;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
-- W.Set_Name ("Test wiki space");
-- T.Manager.Create_Wiki_Space (W);
--
-- P.Set_Name ("The page");
-- P.Set_Title ("The page title");
-- T.Manager.Create_Wiki_Page (W, P, C);
-- T.Assert (P.Is_Inserted, "The new wiki page was not created");
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
-- W.Set_Name ("Test wiki space");
-- T.Manager.Create_Wiki_Space (W);
--
-- P.Set_Name ("The page");
-- P.Set_Title ("The page title");
-- T.Manager.Create_Wiki_Page (W, P, C);
--
-- C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
-- C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
-- C.Set_Save_Comment ("A first version");
-- T.Manager.Create_Wiki_Content (P, C);
-- T.Assert (C.Is_Inserted, "The new wiki content was not created");
-- T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
-- T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
end AWA.Counters.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- 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.Measures;
with Util.Test_Caller;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with AWA.Counters.Definition;
with Security.Contexts;
package body AWA.Counters.Modules.Tests is
package User_Counter is
new AWA.Counters.Definition (AWA.Users.Models.USER_TABLE, "count");
package Session_Counter is
new AWA.Counters.Definition (AWA.Users.Models.SESSION_TABLE, "count");
package Caller is new Util.Test_Caller (Test, "Counters.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment",
Test_Increment'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Increment (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
T.Manager := AWA.Counters.Modules.Get_Counter_Module;
T.Assert (T.Manager /= null, "There is no counter plugin");
T.Manager.Flush;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
end loop;
Util.Measures.Report (S, "AWA.Counters.Increment", 1000);
end;
declare
S : Util.Measures.Stamp;
begin
T.Manager.Flush;
Util.Measures.Report (S, "AWA.Counters.Flush");
end;
-- T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
-- T.Assert (T.Manager /= null, "There is no wiki manager");
--
-- W.Set_Name ("Test wiki space");
-- T.Manager.Create_Wiki_Space (W);
-- T.Assert (W.Is_Inserted, "The new wiki space was not created");
--
-- W.Set_Name ("Test wiki space update");
-- W.Set_Is_Public (True);
-- T.Manager.Save_Wiki_Space (W);
--
-- T.Manager.Load_Wiki_Space (Wiki => W2,
-- Id => W.Get_Id);
-- Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
-- "Invalid wiki space name");
end Test_Increment;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
-- W.Set_Name ("Test wiki space");
-- T.Manager.Create_Wiki_Space (W);
--
-- P.Set_Name ("The page");
-- P.Set_Title ("The page title");
-- T.Manager.Create_Wiki_Page (W, P, C);
-- T.Assert (P.Is_Inserted, "The new wiki page was not created");
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
-- W.Set_Name ("Test wiki space");
-- T.Manager.Create_Wiki_Space (W);
--
-- P.Set_Name ("The page");
-- P.Set_Title ("The page title");
-- T.Manager.Create_Wiki_Page (W, P, C);
--
-- C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
-- C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
-- C.Set_Save_Comment ("A first version");
-- T.Manager.Create_Wiki_Content (P, C);
-- T.Assert (C.Is_Inserted, "The new wiki content was not created");
-- T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
-- T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
end AWA.Counters.Modules.Tests;
|
Update the unit tests
|
Update the unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
61ff80a692da12dbbf61c748d1a8eccbc51c1dfe
|
src/security-controllers.ads
|
src/security-controllers.ads
|
-----------------------------------------------------------------------
-- security-controllers -- Controllers to verify a security permission
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
-- == Security Controller ==
-- The <b>Security.Controllers</b> package defines the security controller used to
-- verify that a given permission is granted. A security controller uses the security
-- context and other controller specific and internal data to verify that the permission
-- is granted.
--
-- To implement a new security controller, one must:
-- <ul>
-- <li>Define a type that implements the <b>Controller</b> interface with the
-- <b>Has_Permission</b> operation
-- <li>Write a function to allocate instances of the given <b>Controller</b> type
-- <li>Register the function under a unique name by using <b>Register_Controller</b>
-- </ul>
--
-- Security controller instances are created when the security policy rules are parsed.
-- These instances are shared across possibly several concurrent requests.
package Security.Controllers is
Invalid_Controller : exception;
-- ------------------------------
-- Security Controller interface
-- ------------------------------
type Controller is limited interface;
type Controller_Access is access all Controller'Class;
-- Checks whether the permission defined by the <b>Handler</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Handler : in Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is abstract;
type Controller_Factory is not null access function return Controller_Access;
-- To keep this implementation simple, a maximum of 32 security controller factory
-- can be registered. ASF provides one based on roles. AWA provides another one
-- based on entity ACLs.
MAX_CONTROLLER_FACTORY : constant Positive := 32;
-- Register in a global table the controller factory under the name <b>Name</b>.
-- When this factory is used, the <b>Factory</b> operation will be called to
-- create new instances of the controller.
procedure Register_Controller (Name : in String;
Factory : in Controller_Factory);
-- Create a security controller by using the controller factory registered under
-- the name <b>Name</b>.
-- Raises <b>Invalid_Controller</b> if the name is not recognized.
function Create_Controller (Name : in String) return Controller_Access;
end Security.Controllers;
|
-----------------------------------------------------------------------
-- security-controllers -- Controllers to verify a security permission
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
-- == Security Controller ==
-- The <b>Security.Controllers</b> package defines the security controller used to
-- verify that a given permission is granted. A security controller uses the security
-- context and other controller specific and internal data to verify that the permission
-- is granted.
--
-- To implement a new security controller, one must:
--
-- * Define a type that implements the <b>Controller</b> interface with the
-- <b>Has_Permission</b> operation
-- * Write a function to allocate instances of the given <b>Controller</b> type
-- * Register the function under a unique name by using <b>Register_Controller</b>
--
-- Security controller instances are created when the security policy rules are parsed.
-- These instances are shared across possibly several concurrent requests.
package Security.Controllers is
Invalid_Controller : exception;
-- ------------------------------
-- Security Controller interface
-- ------------------------------
type Controller is limited interface;
type Controller_Access is access all Controller'Class;
-- Checks whether the permission defined by the <b>Handler</b> controller data is granted
-- by the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
function Has_Permission (Handler : in Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is abstract;
type Controller_Factory is not null access function return Controller_Access;
-- To keep this implementation simple, a maximum of 32 security controller factory
-- can be registered. ASF provides one based on roles. AWA provides another one
-- based on entity ACLs.
MAX_CONTROLLER_FACTORY : constant Positive := 32;
-- Register in a global table the controller factory under the name <b>Name</b>.
-- When this factory is used, the <b>Factory</b> operation will be called to
-- create new instances of the controller.
procedure Register_Controller (Name : in String;
Factory : in Controller_Factory);
-- Create a security controller by using the controller factory registered under
-- the name <b>Name</b>.
-- Raises <b>Invalid_Controller</b> if the name is not recognized.
function Create_Controller (Name : in String) return Controller_Access;
end Security.Controllers;
|
Update the documentation style
|
Update the documentation style
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
e25ec12d060366eb240984dd8d9d2a79fb67c9d8
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Permission is abstract tagged limited null record;
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
private
use Util.Strings;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Permission is abstract tagged limited null record;
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
private
use Util.Strings;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
type Controller_Access_Array_Access is access all Controller_Access_Array;
end Security.Permissions;
|
Remove the unused types and operations
|
Remove the unused types and operations
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
8b659849956eae119c013b2b4d57cbedb1689e25
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package Security.Permissions is
Invalid_Name : exception;
type Permission_Index is new Natural;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Permission (Id : Permission_Index) is tagged limited null record;
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package Security.Permissions is
Invalid_Name : exception;
type Permission_Index is new Natural;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
-- 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 Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
end Security.Permissions;
|
Remove Permission_Type and Permission_Map
|
Remove Permission_Type and Permission_Map
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
915872fcaa45d871ab294f878e7153044d7a0851
|
src/util-serialize-io-csv.ads
|
src/util-serialize-io-csv.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Vectors;
with Util.Streams.Texts;
-- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files.
--
-- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files
package Util.Serialize.IO.CSV is
type Row_Type is new Natural;
type Column_Type is new Positive;
-- ------------------------------
-- CSV Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a CSV output stream.
-- The stream object takes care of the CSV escape rules.
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character);
-- Enable or disable the double quotes by default for strings.
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean);
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new row.
procedure New_Row (Stream : in out Output_Stream);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- CSV Parser
-- ------------------------------
-- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly
-- in Ada records.
type Parser is new Serialize.IO.Parser with private;
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String;
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type);
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the field separator.
function Get_Field_Separator (Handler : in Parser) return Character;
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
function Get_Comment_Separator (Handler : in Parser) return Character;
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True);
-- Parse the stream using the CSV parser.
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
overriding
function Get_Location (Handler : in Parser) return String;
private
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Max_Columns : Column_Type := 1;
Column : Column_Type := 1;
Row : Row_Type := 0;
Separator : Character := ',';
Quote : Boolean := True;
end record;
type Parser is new Util.Serialize.IO.Parser with record
Has_Header : Boolean := True;
Line_Number : Natural := 1;
Row : Row_Type := 0;
Headers : Util.Strings.Vectors.Vector;
Separator : Character := ',';
Comment : Character := ASCII.NUL;
Use_Default_Headers : Boolean := False;
Sink : access Reader'Class;
end record;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Vectors;
with Util.Streams.Texts;
-- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files.
--
-- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files
package Util.Serialize.IO.CSV is
type Row_Type is new Natural;
type Column_Type is new Positive;
-- ------------------------------
-- CSV Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating a CSV output stream.
-- The stream object takes care of the CSV escape rules.
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character);
-- Enable or disable the double quotes by default for strings.
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean);
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean);
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new row.
procedure New_Row (Stream : in out Output_Stream);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Nullables.Nullable_String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- CSV Parser
-- ------------------------------
-- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly
-- in Ada records.
type Parser is new Serialize.IO.Parser with private;
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String;
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type);
-- Set the field separator. The default field separator is the comma (',').
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the field separator.
function Get_Field_Separator (Handler : in Parser) return Character;
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character);
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
function Get_Comment_Separator (Handler : in Parser) return Character;
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True);
-- Parse the stream using the CSV parser.
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class);
-- Get the current location (file and line) to report an error message.
overriding
function Get_Location (Handler : in Parser) return String;
private
type Output_Stream is
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Max_Columns : Column_Type := 1;
Column : Column_Type := 1;
Row : Row_Type := 0;
Separator : Character := ',';
Quote : Boolean := True;
end record;
type Parser is new Util.Serialize.IO.Parser with record
Has_Header : Boolean := True;
Line_Number : Natural := 1;
Row : Row_Type := 0;
Headers : Util.Strings.Vectors.Vector;
Separator : Character := ',';
Comment : Character := ASCII.NUL;
Use_Default_Headers : Boolean := False;
Sink : access Reader'Class;
end record;
end Util.Serialize.IO.CSV;
|
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
|
6b5b0c46ecd7e5f66fd96c5e1ee571a17180c00e
|
awa/regtests/awa-users-services-tests.adb
|
awa/regtests/awa-users-services-tests.adb
|
-----------------------------------------------------------------------
-- users - User creation, password tests
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with ADO;
with ADO.Sessions;
with ADO.SQL;
with ADO.Objects;
with Ada.Calendar;
with AWA.Users.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Users.Services.Tests is
use Util.Tests;
use ADO;
use ADO.Objects;
package Caller is new Util.Test_Caller (Test, "Users.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module",
Test_Get_Module'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session must be created");
T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
-- T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started");
T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date,
S1.Get_Start_Date,
"Invalid start date");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Create_User;
-- ------------------------------
-- Test logout of a user
-- ------------------------------
procedure Test_Logout_User (T : in out Test) is
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
AWA.Tests.Helpers.Users.Logout (Principal);
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (False, "Verify_Session should report a non-existent session");
exception
when Not_Found =>
null;
end;
begin
AWA.Tests.Helpers.Users.Logout (Principal);
T.Assert (False, "Second logout should report a non-existent session");
exception
when Not_Found =>
null;
end;
end Test_Logout_User;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type Ada.Calendar.Time;
Principal : AWA.Tests.Helpers.Users.Test_User;
T1 : Ada.Calendar.Time;
begin
begin
Principal.Email.Set_Email ("[email protected]");
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (False, "Login succeeded with an invalid user name");
exception
when Not_Found =>
null;
end;
-- Create the user
T1 := Ada.Calendar.Clock;
AWA.Tests.Helpers.Users.Create_User (Principal);
AWA.Tests.Helpers.Users.Logout (Principal);
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
-- T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null");
T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date,
S1.Get_Start_Date,
"Invalid start date");
-- Storing a date in the database will loose some precision.
T.Assert (S1.Get_Start_Date >= T1 - 1.0, "Start date is invalid 1");
T.Assert (S1.Get_Start_Date <= T2 + 10.0, "Start date is invalid 3");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Login_User;
-- ------------------------------
-- Test password reset process
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
use type AWA.Users.Principals.Principal_Access;
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
AWA.Tests.Helpers.Users.Logout (Principal);
-- Start the lost password process.
Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email);
AWA.Tests.Helpers.Users.Login (Principal);
-- Get the access key to reset the password
declare
DB : ADO.Sessions.Session := Principal.Manager.Get_Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
-- Find the access key
Query.Set_Filter ("user_id = ?");
Query.Bind_Param (1, Principal.User.Get_Id);
Key.Find (DB, Query, Found);
T.Assert (Found, "Access key for lost_password process not found");
Principal.Manager.Reset_Password (Key => Key.Get_Access_Key,
Password => "newadmin",
IpAddr => "192.168.1.2",
Principal => Principal.Principal);
T.Assert (Principal.Principal /= null, "No principal returned");
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
-- Search the access key again, it must have been removed.
Key.Find (DB, Query, Found);
T.Assert (not Found, "The access key is still present in the database");
end;
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
AWA.Tests.Helpers.Users.Logout (Principal);
end Test_Reset_Password_User;
-- ------------------------------
-- Test Get_User_Module operation
-- ------------------------------
procedure Test_Get_Module (T : in out Test) is
use type AWA.Users.Modules.User_Module_Access;
begin
declare
M : constant AWA.Users.Modules.User_Module_Access := AWA.Users.Modules.Get_User_Module;
begin
T.Assert (M /= null, "Get_User_Module returned null");
end;
declare
S : Util.Measures.Stamp;
M : AWA.Users.Modules.User_Module_Access;
begin
for I in 1 .. 1_000 loop
M := AWA.Users.Modules.Get_User_Module;
end loop;
Util.Measures.Report (S, "Get_User_Module (1000)");
T.Assert (M /= null, "Get_User_Module returned null");
end;
end Test_Get_Module;
end AWA.Users.Services.Tests;
|
-----------------------------------------------------------------------
-- users - User creation, password tests
-- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with Util.Log.Loggers;
with ADO;
with ADO.Sessions;
with ADO.SQL;
with ADO.Objects;
with Ada.Calendar;
with AWA.Users.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Users.Services.Tests is
use Util.Tests;
use ADO;
use ADO.Objects;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Services.Tests");
package Caller is new Util.Test_Caller (Test, "Users.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module",
Test_Get_Module'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session must be created");
T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
-- T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started");
T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date,
S1.Get_Start_Date,
"Invalid start date");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Create_User;
-- ------------------------------
-- Test logout of a user
-- ------------------------------
procedure Test_Logout_User (T : in out Test) is
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
AWA.Tests.Helpers.Users.Logout (Principal);
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (False, "Verify_Session should report a non-existent session");
exception
when Not_Found =>
null;
end;
begin
AWA.Tests.Helpers.Users.Logout (Principal);
T.Assert (False, "Second logout should report a non-existent session");
exception
when Not_Found =>
null;
end;
end Test_Logout_User;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type Ada.Calendar.Time;
Principal : AWA.Tests.Helpers.Users.Test_User;
T1 : Ada.Calendar.Time;
begin
begin
Principal.Email.Set_Email ("[email protected]");
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (False, "Login succeeded with an invalid user name");
exception
when Not_Found =>
null;
end;
-- Create the user
T1 := Ada.Calendar.Clock;
AWA.Tests.Helpers.Users.Create_User (Principal);
Log.Info ("Created user and session is {0}",
ADO.Identifier'Image (Principal.Session.Get_Id));
AWA.Tests.Helpers.Users.Logout (Principal);
delay 1.0;
AWA.Tests.Helpers.Users.Login (Principal);
Log.Info ("Logout and login with session {0}",
ADO.Identifier'Image (Principal.Session.Get_Id));
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
-- T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null");
T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date,
S1.Get_Start_Date,
"Invalid start date");
-- Storing a date in the database will loose some precision.
T.Assert (S1.Get_Start_Date >= T1 - 1.0, "Start date is invalid 1");
T.Assert (S1.Get_Start_Date <= T2 + 10.0, "Start date is invalid 3");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Login_User;
-- ------------------------------
-- Test password reset process
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
use type AWA.Users.Principals.Principal_Access;
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
-- Create the user
AWA.Tests.Helpers.Users.Create_User (Principal);
AWA.Tests.Helpers.Users.Logout (Principal);
-- Start the lost password process.
Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email);
AWA.Tests.Helpers.Users.Login (Principal);
-- Get the access key to reset the password
declare
DB : ADO.Sessions.Session := Principal.Manager.Get_Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
-- Find the access key
Query.Set_Filter ("user_id = ?");
Query.Bind_Param (1, Principal.User.Get_Id);
Key.Find (DB, Query, Found);
T.Assert (Found, "Access key for lost_password process not found");
Principal.Manager.Reset_Password (Key => Key.Get_Access_Key,
Password => "newadmin",
IpAddr => "192.168.1.2",
Principal => Principal.Principal);
T.Assert (Principal.Principal /= null, "No principal returned");
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
-- Search the access key again, it must have been removed.
Key.Find (DB, Query, Found);
T.Assert (not Found, "The access key is still present in the database");
end;
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
AWA.Tests.Helpers.Users.Logout (Principal);
end Test_Reset_Password_User;
-- ------------------------------
-- Test Get_User_Module operation
-- ------------------------------
procedure Test_Get_Module (T : in out Test) is
use type AWA.Users.Modules.User_Module_Access;
begin
declare
M : constant AWA.Users.Modules.User_Module_Access := AWA.Users.Modules.Get_User_Module;
begin
T.Assert (M /= null, "Get_User_Module returned null");
end;
declare
S : Util.Measures.Stamp;
M : AWA.Users.Modules.User_Module_Access;
begin
for I in 1 .. 1_000 loop
M := AWA.Users.Modules.Get_User_Module;
end loop;
Util.Measures.Report (S, "Get_User_Module (1000)");
T.Assert (M /= null, "Get_User_Module returned null");
end;
end Test_Get_Module;
end AWA.Users.Services.Tests;
|
Add some traces for login trouble shotting
|
Add some traces for login trouble shotting
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
c9adb8f5f05609da1a94bb579274ac82379e4e3b
|
src/aws/asf-responses-web.adb
|
src/aws/asf-responses-web.adb
|
-----------------------------------------------------------------------
-- asf.responses.web -- ASF Responses with AWS server
-- 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 AWS.Headers;
with AWS.Messages;
with AWS.Response.Set;
with AWS.Containers.Tables;
package body ASF.Responses.Web is
procedure Initialize (Resp : in out Response) is
begin
Resp.Content.Initialize (Size => 256 * 1024,
Output => Resp'Unchecked_Access,
Input => null);
Resp.Stream := Resp.Content'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
procedure Write (Stream : in out Response;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
AWS.Response.Set.Append_Body (D => Stream.Data,
Item => Buffer);
end Write;
-- ------------------------------
-- Flush the buffer (if any) to the sink.
-- ------------------------------
procedure Flush (Stream : in out Response) is
begin
null;
end Flush;
function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code;
function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code is
use AWS.Messages;
begin
case Status is
when 100 =>
return S100;
when 101 =>
return S101;
when 200 =>
return S200;
when 201 =>
return S201;
when 202 =>
return S202;
when 301 =>
return S301;
when 302 =>
return S302;
when 400 =>
return S400;
when 401 =>
return S401;
when 402 =>
return S402;
when 403 =>
return S403;
when 404 =>
return S404;
when others =>
return S500;
end case;
end To_Status_Code;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Resp : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
Headers : constant AWS.Headers.List := AWS.Response.Header (Resp.Data);
begin
AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (Headers),
";", Process);
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Resp : in Response;
Name : in String) return Boolean is
begin
raise Program_Error with "Contains_Header is not implemented";
return False;
end Contains_Header;
-- ------------------------------
-- Sets a response header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
procedure Set_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
if AWS.Response.Header (Resp.Data, Name)'Length = 0 then
AWS.Response.Set.Add_Header (D => Resp.Data,
Name => Name,
Value => Value);
end if;
end Set_Header;
-- ------------------------------
-- Adds a response header with the given name and value.
-- This method allows response headers to have multiple values.
-- ------------------------------
procedure Add_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
AWS.Response.Set.Add_Header (D => Resp.Data,
Name => Name,
Value => Value);
end Add_Header;
-- ------------------------------
-- Sends a temporary redirect response to the client using the specified redirect
-- location URL. This method can accept relative URLs; the servlet container must
-- convert the relative URL to an absolute URL before sending the response to the
-- client. If the location is relative without a leading '/' the container
-- interprets it as relative to the current request URI. If the location is relative
-- with a leading '/' the container interprets it as relative to the servlet
-- container root.
--
-- If the response has already been committed, this method throws an
-- IllegalStateException. After using this method, the response should be
-- considered to be committed and should not be written to.
-- ------------------------------
procedure Send_Redirect (Resp : in out Response;
Location : in String) is
begin
Response'Class (Resp).Set_Status (SC_FOUND);
Response'Class (Resp).Set_Header (Name => "Location",
Value => Location);
Resp.Redirect := True;
end Send_Redirect;
-- ------------------------------
-- Prepare the response data by collecting the status, content type and message body.
-- ------------------------------
procedure Build (Resp : in out Response) is
begin
if not Resp.Redirect then
AWS.Response.Set.Content_Type (D => Resp.Data,
Value => Resp.Get_Content_Type);
Resp.Content.Flush;
else
AWS.Response.Set.Mode (D => Resp.Data,
Value => AWS.Response.Header);
end if;
AWS.Response.Set.Status_Code (D => Resp.Data,
Value => To_Status_Code (Resp.Get_Status));
end Build;
-- ------------------------------
-- Get the response data
-- ------------------------------
function Get_Data (Resp : in Response) return AWS.Response.Data is
begin
return Resp.Data;
end Get_Data;
end ASF.Responses.Web;
|
-----------------------------------------------------------------------
-- asf.responses.web -- ASF Responses with AWS server
-- 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 AWS.Headers;
with AWS.Messages;
with AWS.Response.Set;
with AWS.Containers.Tables;
package body ASF.Responses.Web is
procedure Initialize (Resp : in out Response) is
begin
Resp.Content.Initialize (Size => 256 * 1024,
Output => Resp'Unchecked_Access,
Input => null);
Resp.Stream := Resp.Content'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
procedure Write (Stream : in out Response;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
AWS.Response.Set.Append_Body (D => Stream.Data,
Item => Buffer);
end Write;
-- ------------------------------
-- Flush the buffer (if any) to the sink.
-- ------------------------------
procedure Flush (Stream : in out Response) is
begin
null;
end Flush;
function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code;
function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code is
use AWS.Messages;
begin
case Status is
when 100 =>
return S100;
when 101 =>
return S101;
when 200 =>
return S200;
when 201 =>
return S201;
when 202 =>
return S202;
when 301 =>
return S301;
when 302 =>
return S302;
when 400 =>
return S400;
when 401 =>
return S401;
when 402 =>
return S402;
when 403 =>
return S403;
when 404 =>
return S404;
when others =>
return S500;
end case;
end To_Status_Code;
-- ------------------------------
-- Iterate over the response headers and executes the <b>Process</b> procedure.
-- ------------------------------
procedure Iterate_Headers (Resp : in Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
Headers : constant AWS.Headers.List := AWS.Response.Header (Resp.Data);
begin
AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (Headers),
";", Process);
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Resp : in Response;
Name : in String) return Boolean is
begin
raise Program_Error with "Contains_Header is not implemented";
return False;
end Contains_Header;
-- ------------------------------
-- Sets a response header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
procedure Set_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
if AWS.Response.Header (Resp.Data, Name)'Length = 0 then
AWS.Response.Set.Add_Header (D => Resp.Data,
Name => Name,
Value => Value);
end if;
end Set_Header;
-- ------------------------------
-- Adds a response header with the given name and value.
-- This method allows response headers to have multiple values.
-- ------------------------------
procedure Add_Header (Resp : in out Response;
Name : in String;
Value : in String) is
begin
AWS.Response.Set.Add_Header (D => Resp.Data,
Name => Name,
Value => Value);
end Add_Header;
-- ------------------------------
-- Sends a temporary redirect response to the client using the specified redirect
-- location URL. This method can accept relative URLs; the servlet container must
-- convert the relative URL to an absolute URL before sending the response to the
-- client. If the location is relative without a leading '/' the container
-- interprets it as relative to the current request URI. If the location is relative
-- with a leading '/' the container interprets it as relative to the servlet
-- container root.
--
-- If the response has already been committed, this method throws an
-- IllegalStateException. After using this method, the response should be
-- considered to be committed and should not be written to.
-- ------------------------------
procedure Send_Redirect (Resp : in out Response;
Location : in String) is
begin
Response'Class (Resp).Set_Status (SC_FOUND);
Response'Class (Resp).Set_Header (Name => "Location",
Value => Location);
Resp.Redirect := True;
end Send_Redirect;
-- ------------------------------
-- Prepare the response data by collecting the status, content type and message body.
-- ------------------------------
procedure Build (Resp : in out Response) is
begin
if not Resp.Redirect then
AWS.Response.Set.Content_Type (D => Resp.Data,
Value => Resp.Get_Content_Type);
Resp.Content.Flush;
if AWS.Response.Is_Empty (Resp.Data) then
AWS.Response.Set.Message_Body (Resp.Data, "");
end if;
else
AWS.Response.Set.Mode (D => Resp.Data,
Value => AWS.Response.Header);
end if;
AWS.Response.Set.Status_Code (D => Resp.Data,
Value => To_Status_Code (Resp.Get_Status));
end Build;
-- ------------------------------
-- Get the response data
-- ------------------------------
function Get_Data (Resp : in Response) return AWS.Response.Data is
begin
return Resp.Data;
end Get_Data;
end ASF.Responses.Web;
|
Fix AWS support - if the response is empty and this is not a redirect, return an empty body.
|
Fix AWS support
- if the response is empty and this is not a redirect, return an empty body.
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
4d91cd8dd0072e4e2124d86aaa650482b35f8fd8
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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;
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, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with ASF.Applications;
with ADO;
with 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;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
private
type Blog_Module is new AWA.Modules.Module with null record;
end AWA.Blogs.Modules;
|
Declare the Load_Image procedure
|
Declare the Load_Image procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
196fe3c13a4409d22d8248f0b95487a7491f3d27
|
orka/src/orka/implementation/orka-rendering-programs-modules.adb
|
orka/src/orka/implementation/orka-rendering-programs-modules.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with GL.Debug;
with Orka.Strings;
with Orka.Terminals;
package body Orka.Rendering.Programs.Modules is
use GL.Debug;
package Messages is new GL.Debug.Messages (Third_Party, Other);
function Trim_Image (Value : Integer) return String is
(Orka.Strings.Trim (Integer'Image (Value)));
procedure Log_Error_With_Source (Text, Info_Log, Message : String) is
package SF renames Ada.Strings.Fixed;
package L1 renames Ada.Characters.Latin_1;
Extra_Rows : constant := 2;
Line_Number_Padding : constant := 2;
Separator : constant String := " | ";
use Orka.Strings;
use SF;
use all type Orka.Terminals.Color;
use all type Orka.Terminals.Style;
begin
declare
Log_Parts : constant Orka.Strings.String_List := Split (Info_Log, ":", 3);
Message_Parts : constant String_List := Split (Trim (+Log_Parts (3)), ": ", 2);
Message_Kind_Color : constant Orka.Terminals.Color :=
(if +Message_Parts (1) = "error" then
Red
elsif +Message_Parts (2) = "warning" then
Yellow
elsif +Message_Parts (2) = "note" then
Cyan
else
Default);
Message_Kind : constant String :=
Orka.Terminals.Colorize (+Message_Parts (1) & ":", Foreground => Message_Kind_Color);
Message_Value : constant String :=
Orka.Terminals.Colorize (+Message_Parts (2), Attribute => Bold);
-------------------------------------------------------------------------
Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF);
Error_Row : constant Positive :=
Positive'Value (+Orka.Strings.Split (+Log_Parts (2), "(", 2) (1));
First_Row : constant Positive := Positive'Max (Lines'First, Error_Row - Extra_Rows);
Last_Row : constant Positive := Positive'Min (Lines'Last, Error_Row + Extra_Rows);
Line_Digits : constant Positive := Trim (Last_Row'Image)'Length + Line_Number_Padding;
begin
Messages.Log (High, Message);
for Row_Index in First_Row .. Last_Row loop
declare
Row_Image : constant String :=
SF.Tail (Trim (Row_Index'Image), Line_Digits);
Row_Image_Colorized : constant String :=
Orka.Terminals.Colorize (Row_Image, Attribute => Dark);
Line_Image : constant String := +Lines (Row_Index);
First_Index_Line : constant Natural :=
SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Forward);
Last_Index_Line : constant Natural :=
SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Backward);
Error_Indicator : constant String :=
Orka.Terminals.Colorize
(Natural'Max (0, First_Index_Line - 1) * " " &
(Last_Index_Line - First_Index_Line + 1) * "^",
Foreground => Green,
Attribute => Bold);
Prefix_Image : constant String :=
(Row_Image'Length + Separator'Length) * " ";
begin
Messages.Log (High, Row_Image_Colorized & Separator & Line_Image);
if Row_Index = Error_Row then
Messages.Log (High, Prefix_Image & Error_Indicator);
Messages.Log (High, Prefix_Image & ">>> " & Message_Kind & " " & Message_Value);
end if;
end;
end loop;
end;
exception
when others =>
-- Continue if parsing Info_Log fails
null;
end Log_Error_With_Source;
procedure Load_And_Compile
(Object : in out Module;
Shader_Kind : GL.Objects.Shaders.Shader_Type;
Location : Resources.Locations.Location_Ptr;
Path : String) is
begin
if Path /= "" then
pragma Assert (Object.Shaders (Shader_Kind).Is_Empty);
declare
Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind);
Source : constant Resources.Byte_Array_Pointers.Pointer
:= Location.Read_Data (Path);
Text : String renames Resources.Convert (Source.Get);
begin
Shader.Set_Source (Text);
Shader.Compile;
if not Shader.Compile_Status then
declare
Log : constant String := Shader.Info_Log;
begin
Log_Error_With_Source (Text, Log, "Compiling shader " & Path & " failed:");
raise Shader_Compile_Error with Path & ":" & Log;
end;
end if;
Messages.Log (Notification, "Compiled shader " & Path);
Messages.Log (Notification, " size: " & Trim_Image (Orka.Strings.Lines (Text)) &
" lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)");
Messages.Log (Notification, " kind: " & Shader_Kind'Image);
Object.Shaders (Shader_Kind).Replace_Element (Shader);
end;
end if;
end Load_And_Compile;
procedure Set_And_Compile
(Object : in out Module;
Shader_Kind : GL.Objects.Shaders.Shader_Type;
Source : String) is
begin
if Source /= "" then
pragma Assert (Object.Shaders (Shader_Kind).Is_Empty);
declare
Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind);
begin
Shader.Set_Source (Source);
Shader.Compile;
if not Shader.Compile_Status then
declare
Log : constant String := Shader.Info_Log;
begin
Log_Error_With_Source (Source, Log,
"Compiling " & Shader_Kind'Image & " shader failed:");
raise Shader_Compile_Error with Shader_Kind'Image & ":" & Log;
end;
end if;
Messages.Log (Notification, "Compiled string with " &
Trim_Image (Source'Length) & " characters");
Messages.Log (Notification, " size: " &
Trim_Image (Orka.Strings.Lines (Source)) & " lines");
Messages.Log (Notification, " kind: " & Shader_Kind'Image);
Object.Shaders (Shader_Kind).Replace_Element (Shader);
end;
end if;
end Set_And_Compile;
function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "")
return Module
is
use GL.Objects.Shaders;
begin
return Result : Module do
Set_And_Compile (Result, Vertex_Shader, VS);
Set_And_Compile (Result, Tess_Control_Shader, TCS);
Set_And_Compile (Result, Tess_Evaluation_Shader, TES);
Set_And_Compile (Result, Geometry_Shader, GS);
Set_And_Compile (Result, Fragment_Shader, FS);
Set_And_Compile (Result, Compute_Shader, CS);
end return;
end Create_Module_From_Sources;
function Create_Module
(Location : Resources.Locations.Location_Ptr;
VS, TCS, TES, GS, FS, CS : String := "") return Module
is
use GL.Objects.Shaders;
begin
return Result : Module do
Load_And_Compile (Result, Vertex_Shader, Location, VS);
Load_And_Compile (Result, Tess_Control_Shader, Location, TCS);
Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES);
Load_And_Compile (Result, Geometry_Shader, Location, GS);
Load_And_Compile (Result, Fragment_Shader, Location, FS);
Load_And_Compile (Result, Compute_Shader, Location, CS);
end return;
end Create_Module;
procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is
use GL.Objects.Shaders;
procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is
Holder : Shader_Holder.Holder renames Subject.Shaders (Stage);
begin
if not Holder.Is_Empty then
Program.GL_Program.Attach (Holder.Element);
end if;
end Attach;
begin
for Module of Modules loop
Attach (Module, Vertex_Shader);
Attach (Module, Tess_Control_Shader);
Attach (Module, Tess_Evaluation_Shader);
Attach (Module, Geometry_Shader);
Attach (Module, Fragment_Shader);
Attach (Module, Compute_Shader);
end loop;
end Attach_Shaders;
procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is
use GL.Objects.Shaders;
procedure Detach (Holder : Shader_Holder.Holder) is
begin
if not Holder.Is_Empty then
Program.GL_Program.Detach (Holder.Element);
end if;
end Detach;
begin
for Module of Modules loop
Detach (Module.Shaders (Vertex_Shader));
Detach (Module.Shaders (Tess_Control_Shader));
Detach (Module.Shaders (Tess_Evaluation_Shader));
Detach (Module.Shaders (Geometry_Shader));
Detach (Module.Shaders (Fragment_Shader));
Detach (Module.Shaders (Compute_Shader));
end loop;
end Detach_Shaders;
end Orka.Rendering.Programs.Modules;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with GL.Debug;
with Orka.Strings;
with Orka.Terminals;
package body Orka.Rendering.Programs.Modules is
use GL.Debug;
package Messages is new GL.Debug.Messages (Third_Party, Other);
function Trim_Image (Value : Integer) return String is
(Orka.Strings.Trim (Integer'Image (Value)));
package L1 renames Ada.Characters.Latin_1;
use Orka.Strings;
procedure Log_Error_With_Source (Text, Info_Log, Message : String) is
package SF renames Ada.Strings.Fixed;
Extra_Rows : constant := 1;
Line_Number_Padding : constant := 2;
Separator : constant String := " | ";
use SF;
use all type Orka.Terminals.Color;
use all type Orka.Terminals.Style;
begin
declare
Log_Parts : constant Orka.Strings.String_List := Split (Info_Log, ":", 3);
Message_Parts : constant String_List := Split (Trim (+Log_Parts (3)), ": ", 2);
Message_Kind_Color : constant Orka.Terminals.Color :=
(if +Message_Parts (1) = "error" then
Red
elsif +Message_Parts (1) = "warning" then
Yellow
elsif +Message_Parts (1) = "note" then
Cyan
else
Default);
Message_Kind : constant String :=
Orka.Terminals.Colorize (+Message_Parts (1) & ":", Foreground => Message_Kind_Color);
Message_Value : constant String :=
Orka.Terminals.Colorize (+Message_Parts (2), Attribute => Bold);
-------------------------------------------------------------------------
Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF);
Error_Row : constant Positive :=
Positive'Value (+Orka.Strings.Split (+Log_Parts (2), "(", 2) (1));
First_Row : constant Positive := Positive'Max (Lines'First, Error_Row - Extra_Rows);
Last_Row : constant Positive := Positive'Min (Lines'Last, Error_Row + Extra_Rows);
Line_Digits : constant Positive := Trim (Last_Row'Image)'Length + Line_Number_Padding;
begin
Messages.Log (High, Message);
for Row_Index in First_Row .. Last_Row loop
declare
Row_Image : constant String :=
SF.Tail (Trim (Row_Index'Image), Line_Digits);
Row_Image_Colorized : constant String :=
Orka.Terminals.Colorize (Row_Image, Attribute => Dark);
Line_Image : constant String := +Lines (Row_Index);
First_Index_Line : constant Natural :=
SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Forward);
Last_Index_Line : constant Natural :=
SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Backward);
Error_Indicator : constant String :=
Orka.Terminals.Colorize
(Natural'Max (0, First_Index_Line - 1) * " " &
(Last_Index_Line - First_Index_Line + 1) * "^",
Foreground => Green,
Attribute => Bold);
Prefix_Image : constant String :=
(Row_Image'Length + Separator'Length) * " ";
begin
Messages.Log (High, Row_Image_Colorized & Separator & Line_Image);
if Row_Index = Error_Row then
Messages.Log (High, Prefix_Image & Error_Indicator);
Messages.Log (High, Prefix_Image & ">>> " & Message_Kind & " " & Message_Value);
end if;
end;
end loop;
end;
exception
when others =>
-- Continue if parsing Info_Log fails
null;
end Log_Error_With_Source;
procedure Load_And_Compile
(Object : in out Module;
Shader_Kind : GL.Objects.Shaders.Shader_Type;
Location : Resources.Locations.Location_Ptr;
Path : String) is
begin
if Path /= "" then
pragma Assert (Object.Shaders (Shader_Kind).Is_Empty);
declare
Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind);
Source : constant Resources.Byte_Array_Pointers.Pointer
:= Location.Read_Data (Path);
Text : String renames Resources.Convert (Source.Get);
begin
Shader.Set_Source (Text);
Shader.Compile;
if not Shader.Compile_Status then
declare
Log : constant String := Shader.Info_Log;
Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF);
begin
for Part of Log_Parts loop
Log_Error_With_Source (Text, +Part, "Compiling shader " & Path & " failed:");
end loop;
raise Shader_Compile_Error with Path & ":" & Log;
end;
end if;
Messages.Log (Notification, "Compiled shader " & Path);
Messages.Log (Notification, " size: " & Trim_Image (Orka.Strings.Lines (Text)) &
" lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)");
Messages.Log (Notification, " kind: " & Shader_Kind'Image);
Object.Shaders (Shader_Kind).Replace_Element (Shader);
end;
end if;
end Load_And_Compile;
procedure Set_And_Compile
(Object : in out Module;
Shader_Kind : GL.Objects.Shaders.Shader_Type;
Source : String) is
begin
if Source /= "" then
pragma Assert (Object.Shaders (Shader_Kind).Is_Empty);
declare
Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind);
begin
Shader.Set_Source (Source);
Shader.Compile;
if not Shader.Compile_Status then
declare
Log : constant String := Shader.Info_Log;
Log_Parts : constant Orka.Strings.String_List := Split (Log, "" & L1.LF);
begin
for Part of Log_Parts loop
Log_Error_With_Source (Source, +Part,
"Compiling " & Shader_Kind'Image & " shader failed:");
end loop;
raise Shader_Compile_Error with Shader_Kind'Image & ":" & Log;
end;
end if;
Messages.Log (Notification, "Compiled string with " &
Trim_Image (Source'Length) & " characters");
Messages.Log (Notification, " size: " &
Trim_Image (Orka.Strings.Lines (Source)) & " lines");
Messages.Log (Notification, " kind: " & Shader_Kind'Image);
Object.Shaders (Shader_Kind).Replace_Element (Shader);
end;
end if;
end Set_And_Compile;
function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "")
return Module
is
use GL.Objects.Shaders;
begin
return Result : Module do
Set_And_Compile (Result, Vertex_Shader, VS);
Set_And_Compile (Result, Tess_Control_Shader, TCS);
Set_And_Compile (Result, Tess_Evaluation_Shader, TES);
Set_And_Compile (Result, Geometry_Shader, GS);
Set_And_Compile (Result, Fragment_Shader, FS);
Set_And_Compile (Result, Compute_Shader, CS);
end return;
end Create_Module_From_Sources;
function Create_Module
(Location : Resources.Locations.Location_Ptr;
VS, TCS, TES, GS, FS, CS : String := "") return Module
is
use GL.Objects.Shaders;
begin
return Result : Module do
Load_And_Compile (Result, Vertex_Shader, Location, VS);
Load_And_Compile (Result, Tess_Control_Shader, Location, TCS);
Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES);
Load_And_Compile (Result, Geometry_Shader, Location, GS);
Load_And_Compile (Result, Fragment_Shader, Location, FS);
Load_And_Compile (Result, Compute_Shader, Location, CS);
end return;
end Create_Module;
procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is
use GL.Objects.Shaders;
procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is
Holder : Shader_Holder.Holder renames Subject.Shaders (Stage);
begin
if not Holder.Is_Empty then
Program.GL_Program.Attach (Holder.Element);
end if;
end Attach;
begin
for Module of Modules loop
Attach (Module, Vertex_Shader);
Attach (Module, Tess_Control_Shader);
Attach (Module, Tess_Evaluation_Shader);
Attach (Module, Geometry_Shader);
Attach (Module, Fragment_Shader);
Attach (Module, Compute_Shader);
end loop;
end Attach_Shaders;
procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is
use GL.Objects.Shaders;
procedure Detach (Holder : Shader_Holder.Holder) is
begin
if not Holder.Is_Empty then
Program.GL_Program.Detach (Holder.Element);
end if;
end Detach;
begin
for Module of Modules loop
Detach (Module.Shaders (Vertex_Shader));
Detach (Module.Shaders (Tess_Control_Shader));
Detach (Module.Shaders (Tess_Evaluation_Shader));
Detach (Module.Shaders (Geometry_Shader));
Detach (Module.Shaders (Fragment_Shader));
Detach (Module.Shaders (Compute_Shader));
end loop;
end Detach_Shaders;
end Orka.Rendering.Programs.Modules;
|
Handle and print multiple errors in the info log of a shader
|
orka: Handle and print multiple errors in the info log of a shader
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
edd706c0d279ad21f36f3fc520889bc536a3a09f
|
src/security-random.adb
|
src/security-random.adb
|
-----------------------------------------------------------------------
-- security-random -- Random numbers for nonce, secret keys, token generation
-- 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 Interfaces.C;
with Ada.Calendar;
with Ada.Calendar.Conversions;
with Util.Encoders.Base64;
package body Security.Random is
use Interfaces;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
overriding
procedure Initialize (Gen : in out Generator) is
begin
Gen.Rand.Reset;
end Initialize;
-- ------------------------------
-- Fill the array with pseudo-random numbers.
-- ------------------------------
procedure Generate (Gen : in out Generator;
Into : out Ada.Streams.Stream_Element_Array) is
begin
Gen.Rand.Generate (Into);
end Generate;
-- ------------------------------
-- Generate a random sequence of bits and convert the result
-- into a string in base64url.
-- ------------------------------
function Generate (Gen : in out Generator'Class;
Bits : in Positive) return String is
use type Ada.Streams.Stream_Element_Offset;
Rand_Count : constant Ada.Streams.Stream_Element_Offset
:= Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32));
Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1);
Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3);
Encoder : Util.Encoders.Base64.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
-- Generate the random sequence.
Gen.Generate (Rand);
-- Encode the random stream in base64url and save it into the result string.
Encoder.Set_URL_Mode (True);
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
declare
Result : String (1 .. Natural (Encoded + 1));
begin
for I in 0 .. Encoded loop
Result (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
return Result;
end;
end Generate;
-- ------------------------------
-- Generate a random sequence of bits, convert the result
-- into a string in base64url and append it to the buffer.
-- ------------------------------
procedure Generate (Gen : in out Generator'Class;
Bits : in Positive;
Into : in out Ada.Strings.Unbounded.Unbounded_String) is
use type Ada.Streams.Stream_Element_Offset;
Rand_Count : constant Ada.Streams.Stream_Element_Offset
:= Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32));
Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1);
Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3);
Encoder : Util.Encoders.Base64.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
-- Generate the random sequence.
Gen.Generate (Rand);
-- Encode the random stream in base64url and save it into the result string.
Encoder.Set_URL_Mode (True);
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
for I in 0 .. Encoded loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Buffer (I)));
end loop;
end Generate;
-- Protected type to allow using the random generator by several tasks.
protected body Raw_Generator is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
Size : constant Ada.Streams.Stream_Element_Offset := Into'Last / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Rand);
begin
Into (4 * I) := Stream_Element (Value and 16#0FF#);
Into (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Into (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Into (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate;
procedure Reset is
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
S : constant Ada.Calendar.Day_Duration := Ada.Calendar.Seconds (Now);
Sec : Interfaces.C.long;
Nsec : Interfaces.C.long;
begin
Ada.Calendar.Conversions.To_Struct_Timespec (S, Sec, Nsec);
Id_Random.Reset (Rand, Integer (Unsigned_32 (Sec) xor Unsigned_32 (Nsec)));
end Reset;
end Raw_Generator;
end Security.Random;
|
-----------------------------------------------------------------------
-- security-random -- Random numbers for nonce, secret keys, token generation
-- 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 Interfaces.C;
with Ada.Calendar;
with Ada.Calendar.Conversions;
with Util.Encoders.Base64;
package body Security.Random is
use Interfaces;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
overriding
procedure Initialize (Gen : in out Generator) is
begin
Gen.Rand.Reset;
end Initialize;
-- ------------------------------
-- Fill the array with pseudo-random numbers.
-- ------------------------------
procedure Generate (Gen : in out Generator;
Into : out Ada.Streams.Stream_Element_Array) is
begin
Gen.Rand.Generate (Into);
end Generate;
-- ------------------------------
-- Generate a random sequence of bits and convert the result
-- into a string in base64url.
-- ------------------------------
function Generate (Gen : in out Generator'Class;
Bits : in Positive) return String is
use type Ada.Streams.Stream_Element_Offset;
Rand_Count : constant Ada.Streams.Stream_Element_Offset
:= Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32));
Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1);
Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3);
Encoder : Util.Encoders.Base64.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
-- Generate the random sequence.
Gen.Generate (Rand);
-- Encode the random stream in base64url and save it into the result string.
Encoder.Set_URL_Mode (True);
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
declare
Result : String (1 .. Natural (Encoded + 1));
begin
for I in 0 .. Encoded loop
Result (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
return Result;
end;
end Generate;
-- ------------------------------
-- Generate a random sequence of bits, convert the result
-- into a string in base64url and append it to the buffer.
-- ------------------------------
procedure Generate (Gen : in out Generator'Class;
Bits : in Positive;
Into : in out Ada.Strings.Unbounded.Unbounded_String) is
use type Ada.Streams.Stream_Element_Offset;
Rand_Count : constant Ada.Streams.Stream_Element_Offset
:= Ada.Streams.Stream_Element_Offset (4 * ((Bits + 31) / 32));
Rand : Ada.Streams.Stream_Element_Array (0 .. Rand_Count - 1);
Buffer : Ada.Streams.Stream_Element_Array (0 .. Rand_Count * 3);
Encoder : Util.Encoders.Base64.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
-- Generate the random sequence.
Gen.Generate (Rand);
-- Encode the random stream in base64url and save it into the result string.
Encoder.Set_URL_Mode (True);
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
for I in 0 .. Encoded loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Buffer (I)));
end loop;
end Generate;
-- Protected type to allow using the random generator by several tasks.
protected body Raw_Generator is
procedure Generate (Into : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
Size : constant Ada.Streams.Stream_Element_Offset := Into'Length / 4;
Remain : constant Ada.Streams.Stream_Element_Offset := Into'Length mod 4;
Value : Unsigned_32;
begin
-- Generate the random sequence (fill 32-bits at a time for each random call).
for I in 0 .. Size - 1 loop
Value := Id_Random.Random (Rand);
Into (Into'First + 4 * I) := Stream_Element (Value and 16#0FF#);
Into (Into'First + 4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Into (Into'First + 4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Into (Into'First + 4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end loop;
-- Fill the remaining bytes.
if Remain > 0 then
Value := Id_Random.Random (Rand);
for I in 0 .. Remain - 1 loop
Into (Into'Last - I) := Stream_Element (Value and 16#0FF#);
Value := Shift_Right (Value, 8);
end loop;
end if;
end Generate;
procedure Reset is
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
S : constant Ada.Calendar.Day_Duration := Ada.Calendar.Seconds (Now);
Sec : Interfaces.C.long;
Nsec : Interfaces.C.long;
begin
Ada.Calendar.Conversions.To_Struct_Timespec (S, Sec, Nsec);
Id_Random.Reset (Rand, Integer (Unsigned_32 (Sec) xor Unsigned_32 (Nsec)));
end Reset;
end Raw_Generator;
end Security.Random;
|
Update the Generate procedure implementation to correctly fill arrays not aligned on 32-bits
|
Update the Generate procedure implementation to correctly fill arrays
not aligned on 32-bits
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
41fddc70e1ac01bcffe6178f9eecbbb5534c41e4
|
tests/natools-smaz-tests.adb
|
tests/natools-smaz-tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-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. --
------------------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Natools.Smaz.Original;
package body Natools.Smaz.Tests is
function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Image (S : Ada.Streams.Stream_Element_Array) return String is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Image;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String := Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String := Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Roundtrip_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Sample_Strings (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Sample_Strings (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109,
112, 108, 51, 51, 51));
Roundtrip_Test (Test, Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings;
end Natools.Smaz.Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-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. --
------------------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Natools.Smaz.Original;
package body Natools.Smaz.Tests is
function Image (S : Ada.Streams.Stream_Element_Array) return String;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array);
------------------------------
-- Local Helper Subprograms --
------------------------------
function Image (S : Ada.Streams.Stream_Element_Array) return String is
use Ada.Strings.Unbounded;
Result : Unbounded_String;
begin
for I in S'Range loop
Append (Result, Ada.Streams.Stream_Element'Image (S (I)));
end loop;
return To_String (Result);
end Image;
procedure Roundtrip_Test
(Test : in out NT.Test;
Dict : in Dictionary;
Decompressed : in String;
Compressed : in Ada.Streams.Stream_Element_Array)
is
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
begin
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Decompressed);
begin
First_OK := True;
if Buffer /= Compressed then
Test.Fail ("Bad compression of """ & Decompressed & '"');
Test.Info ("Found: " & Image (Buffer));
Test.Info ("Expected:" & Image (Compressed));
declare
Round : constant String := Decompress (Dict, Buffer);
begin
if Round /= Decompressed then
Test.Info ("Roundtrip failed, got: """ & Round & '"');
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of """ & Decompressed & '"');
end if;
Test.Report_Exception (Error, NT.Fail);
end;
declare
First_OK : Boolean := False;
begin
declare
Buffer : constant String := Decompress (Dict, Compressed);
begin
First_OK := True;
if Buffer /= Decompressed then
Test.Fail ("Bad decompression of " & Image (Compressed));
Test.Info ("Found: """ & Buffer & '"');
Test.Info ("Expected:""" & Decompressed & '"');
declare
Round : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Buffer);
begin
if Round /= Compressed then
Test.Info ("Roundtrip failed, got: " & Image (Round));
else
Test.Info ("Roundtrip OK");
end if;
end;
end if;
end;
exception
when Error : others =>
if not First_OK then
Test.Info ("During compression of " & Image (Compressed));
end if;
Test.Report_Exception (Error, NT.Fail);
end;
end Roundtrip_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Sample_Strings (Report);
end All_Tests;
----------------------
-- Individual Tests --
----------------------
procedure Sample_Strings (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Roundtrip on sample strings");
begin
Roundtrip_Test (Test, Original.Dictionary,
"This is a small string",
(254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70));
Roundtrip_Test (Test, Original.Dictionary,
"foobar",
(220, 6, 90, 79));
Roundtrip_Test (Test, Original.Dictionary,
"the end",
(1, 171, 61));
Roundtrip_Test (Test, Original.Dictionary,
"not-a-g00d-Exampl333",
(132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109,
112, 108, 51, 51, 51));
Roundtrip_Test (Test, Original.Dictionary,
"Smaz is a simple compression library",
(254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166,
107, 205, 8, 90, 130, 12, 83));
Roundtrip_Test (Test, Original.Dictionary,
"Nothing is more difficult, and therefore more precious, "
& "than to be able to decide",
(254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3,
148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203,
143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2));
Roundtrip_Test (Test, Original.Dictionary,
"this is an example of what works very well with smaz",
(155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254,
107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219));
Roundtrip_Test (Test, Original.Dictionary,
"1000 numbers 2000 will 10 20 30 compress very little",
(255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48,
48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51,
48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87));
Roundtrip_Test (Test, Original.Dictionary,
": : : :",
(255, 6, 58, 32, 58, 32, 58, 32, 58));
exception
when Error : others => Test.Report_Exception (Error);
end Sample_Strings;
end Natools.Smaz.Tests;
|
add a test case showing bug in compressed size estimation
|
smaz-tests: add a test case showing bug in compressed size estimation
|
Ada
|
isc
|
faelys/natools
|
6f0741687caae55b49d32577916267d177aefd1b
|
src/asf-sessions-factory.ads
|
src/asf-sessions-factory.ads
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Strings;
with Ada.Strings.Unbounded;
with Util.Concurrent.Locks;
with Ada.Containers.Hashed_Maps;
with Ada.Numerics.Discrete_Random;
with Interfaces;
with Ada.Streams;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package ASF.Sessions.Factory is
type Session_Factory is tagged limited private;
-- Create a new session
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session);
-- 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);
-- Deletes the session.
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out 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);
-- 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;
-- 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);
private
use Util.Strings;
package Session_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Name_Access,
Element_Type => Session,
Hash => Hash,
Equivalent_Keys => Util.Strings.Equivalent_Keys);
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
type Session_Factory is new Ada.Finalization.Limited_Controlled with record
Lock : Util.Concurrent.Locks.RW_Lock;
-- Id to session map.
Sessions : Session_Maps.Map;
-- Max inactive time in seconds.
Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT;
-- Random number generator used for ID generation.
Random : Id_Random.Generator;
-- Number of 32-bit random numbers used for the ID generation.
Id_Size : Ada.Streams.Stream_Element_Offset := 8;
end record;
-- Initialize the session factory.
overriding
procedure Initialize (Factory : in out Session_Factory);
end ASF.Sessions.Factory;
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Strings;
with Ada.Strings.Unbounded;
with Util.Concurrent.Locks;
with Ada.Containers.Hashed_Maps;
with Ada.Numerics.Discrete_Random;
with Interfaces;
with Ada.Streams;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package ASF.Sessions.Factory is
type Session_Factory is new Ada.Finalization.Limited_Controlled with private;
-- Create a new session
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session);
-- 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);
-- Deletes the session.
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out 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);
-- 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;
-- 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);
private
use Util.Strings;
package Session_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Name_Access,
Element_Type => Session,
Hash => Hash,
Equivalent_Keys => Util.Strings.Equivalent_Keys);
package Id_Random is new Ada.Numerics.Discrete_Random (Interfaces.Unsigned_32);
type Session_Factory is new Ada.Finalization.Limited_Controlled with record
Lock : Util.Concurrent.Locks.RW_Lock;
-- Id to session map.
Sessions : Session_Maps.Map;
-- Max inactive time in seconds.
Max_Inactive : Duration := DEFAULT_INACTIVE_TIMEOUT;
-- Random number generator used for ID generation.
Random : Id_Random.Generator;
-- Number of 32-bit random numbers used for the ID generation.
Id_Size : Ada.Streams.Stream_Element_Offset := 8;
end record;
-- Initialize the session factory.
overriding
procedure Initialize (Factory : in out Session_Factory);
end ASF.Sessions.Factory;
|
Fix compilation issue: the Session_Factory must expose the Finalize procedure so that it can be overriden by derived types.
|
Fix compilation issue: the Session_Factory must expose the Finalize procedure
so that it can be overriden by derived types.
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
ca912d8d6e24c91426bd81c0dd61563eca51c478
|
awa/plugins/awa-storages/src/awa-storages-modules.ads
|
awa/plugins/awa-storages/src/awa-storages-modules.ads
|
-----------------------------------------------------------------------
-- awa-storages-modules -- Storage management module
-- Copyright (C) 2012, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with AWA.Modules;
with AWA.Storages.Services;
with AWA.Storages.Servlets;
-- == Storage Module ==
-- The `Storage_Module` type represents the storage module. An instance of the storage
-- module must be declared and registered when the application is created and initialized.
-- The storage module is associated with the storage service which provides and implements
-- the storage management operations.
--
-- @include-permission storages.xml
-- @include-config storages.xml
package AWA.Storages.Modules is
NAME : constant String := "storages";
type Storage_Module is new AWA.Modules.Module with private;
type Storage_Module_Access is access all Storage_Module'Class;
-- Initialize the storage module.
overriding
procedure Initialize (Plugin : in out Storage_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the storage manager.
function Get_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access;
-- Create a storage manager. This operation can be overridden to provide another
-- storage service implementation.
function Create_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access;
-- Get the storage module instance associated with the current application.
function Get_Storage_Module return Storage_Module_Access;
-- Get the storage manager instance associated with the current application.
function Get_Storage_Manager return Services.Storage_Service_Access;
private
type Storage_Module is new AWA.Modules.Module with record
Manager : Services.Storage_Service_Access := null;
Storage_Servlet : aliased AWA.Storages.Servlets.Storage_Servlet;
end record;
end AWA.Storages.Modules;
|
-----------------------------------------------------------------------
-- awa-storages-modules -- Storage management module
-- Copyright (C) 2012, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with AWA.Modules;
with AWA.Storages.Services;
with AWA.Storages.Servlets;
-- == Storage Module ==
-- The `Storage_Module` type represents the storage module. An instance of the storage
-- module must be declared and registered when the application is created and initialized.
-- The storage module is associated with the storage service which provides and implements
-- the storage management operations.
--
-- @include-permission storages.xml
-- @include-config storages.xml
package AWA.Storages.Modules is
NAME : constant String := "storages";
type Storage_Module is new AWA.Modules.Module with private;
type Storage_Module_Access is access all Storage_Module'Class;
-- Initialize the storage module.
overriding
procedure Initialize (Plugin : in out Storage_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 Storage_Module;
Props : in ASF.Applications.Config);
-- Get the storage manager.
function Get_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access;
-- Create a storage manager. This operation can be overridden to provide another
-- storage service implementation.
function Create_Storage_Manager (Plugin : in Storage_Module)
return Services.Storage_Service_Access;
-- Get the storage module instance associated with the current application.
function Get_Storage_Module return Storage_Module_Access;
-- Get the storage manager instance associated with the current application.
function Get_Storage_Manager return Services.Storage_Service_Access;
private
type Storage_Module is new AWA.Modules.Module with record
Manager : Services.Storage_Service_Access := null;
Storage_Servlet : aliased AWA.Storages.Servlets.Storage_Servlet;
end record;
end AWA.Storages.Modules;
|
Add Configure procedure to configure the storage module
|
Add Configure procedure to configure the storage module
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
46a98c7dfe7ceae8672bb7f2a6575f13780999e1
|
awa/samples/src/atlas-applications.ads
|
awa/samples/src/atlas-applications.ads
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Filters.Dump;
with ASF.Servlets.Measures;
with ASF.Security.Servlets;
with ASF.Converters.Sizes;
with AWA.Users.Servlets;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Applications;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Services.Filters;
with AWA.Converters.Dates;
with Atlas.Microblog.Modules;
package Atlas.Applications is
CONFIG_PATH : constant String := "/atlas";
CONTEXT_PATH : constant String := "/atlas";
ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas";
-- 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;
-- EL function to convert an Email address to a Gravatar image.
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
type Application is new AWA.Applications.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application.
procedure Initialize (App : in Application_Access);
-- 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);
-- 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 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);
private
type Application is new AWA.Applications.Application with record
Self : Application_Access;
-- Application servlets and filters (add new servlet and filter instances here).
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Authentication servlet and filter.
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet;
-- Converters shared by web requests.
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Size_Converter : aliased ASF.Converters.Sizes.Size_Converter;
-- The application modules.
User_Module : aliased AWA.Users.Modules.User_Module;
Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module;
Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
Mail_Module : aliased AWA.Mail.Modules.Mail_Module;
Storage_Module : aliased AWA.Storages.Modules.Storage_Module;
Image_Module : aliased AWA.Images.Modules.Image_Module;
Question_Module : aliased AWA.Questions.Modules.Question_Module;
Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module;
-- XXX_Module : aliased Atlas.XXX.Module.XXX_Module;
end record;
end Atlas.Applications;
|
-----------------------------------------------------------------------
-- atlas -- atlas applications
-----------------------------------------------------------------------
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Filters.Dump;
with ASF.Servlets.Measures;
with ASF.Security.Servlets;
with ASF.Converters.Sizes;
with AWA.Users.Servlets;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Applications;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Services.Filters;
with AWA.Converters.Dates;
with Atlas.Microblog.Modules;
package Atlas.Applications is
CONFIG_PATH : constant String := "/atlas";
CONTEXT_PATH : constant String := "/atlas";
ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas";
-- 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;
-- EL function to convert an Email address to a Gravatar image.
function To_Gravatar_Link (Email : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
type Application is new AWA.Applications.Application with private;
type Application_Access is access all Application'Class;
-- Initialize the application.
procedure Initialize (App : in Application_Access);
-- 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);
-- 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 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);
private
type Application is new AWA.Applications.Application with record
Self : Application_Access;
-- Application servlets and filters (add new servlet and filter instances here).
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Service_Filter : aliased AWA.Services.Filters.Service_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Authentication servlet and filter.
Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet;
-- Converters shared by web requests.
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Size_Converter : aliased ASF.Converters.Sizes.Size_Converter;
-- The application modules.
User_Module : aliased AWA.Users.Modules.User_Module;
Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module;
Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
Mail_Module : aliased AWA.Mail.Modules.Mail_Module;
Storage_Module : aliased AWA.Storages.Modules.Storage_Module;
Image_Module : aliased AWA.Images.Modules.Image_Module;
Vote_Module : aliased AWA.Votes.Modules.Vote_Module;
Question_Module : aliased AWA.Questions.Modules.Question_Module;
Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module;
-- XXX_Module : aliased Atlas.XXX.Module.XXX_Module;
end record;
end Atlas.Applications;
|
Add the vote plugin
|
Add the vote plugin
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0f5fe46046cb73423e08fd4416226a0e15033eef
|
orka_plugin_gltf/src/orka-gltf-meshes.ads
|
orka_plugin_gltf/src/orka-gltf-meshes.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Types;
with Orka.Containers.Bounded_Vectors;
package Orka.glTF.Meshes is
pragma Preelaborate;
subtype Primitive_Mode is GL.Types.Connection_Mode
range GL.Types.Points .. GL.Types.Triangle_Strip;
type Attribute_Kind is (Position, Normal, Texcoord_0);
type Attribute_Array is array (Attribute_Kind) of Natural;
type Primitive is record
Attributes : Attribute_Array;
Indices : Natural_Optional;
Material : Natural_Optional;
Mode : Primitive_Mode;
end record;
type Mesh is record
-- Orka.Resources.Models.glTF can handle only one primitive per mesh
Primitives : Primitive;
Name : Name_Strings.Bounded_String;
end record;
package Mesh_Vectors is new Orka.Containers.Bounded_Vectors (Natural, Mesh);
function Get_Meshes
(Meshes : Types.JSON_Value) return Mesh_Vectors.Vector;
end Orka.glTF.Meshes;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Types;
with Orka.Containers.Bounded_Vectors;
package Orka.glTF.Meshes is
pragma Preelaborate;
subtype Primitive_Mode is GL.Types.Connection_Mode
range GL.Types.Points .. GL.Types.Triangle_Strip;
type Attribute_Kind is (Position, Normal, Texcoord_0);
-- TODO Other kinds: Tangent, Texcoord_1, Color_0, Joints_0, Weights_0
type Attribute_Array is array (Attribute_Kind) of Natural;
-- FIXME Support more attribute kinds and use Boolean to indicate whether it is used
type Primitive is record
Attributes : Attribute_Array;
Indices : Natural_Optional;
Material : Natural_Optional;
Mode : Primitive_Mode;
end record;
type Mesh is record
-- Orka.Resources.Models.glTF can handle only one primitive per mesh
Primitives : Primitive;
Name : Name_Strings.Bounded_String;
end record;
package Mesh_Vectors is new Orka.Containers.Bounded_Vectors (Natural, Mesh);
function Get_Meshes
(Meshes : Types.JSON_Value) return Mesh_Vectors.Vector;
end Orka.glTF.Meshes;
|
Add some TODOs/FIXMEs to package Orka.glTF.Meshes
|
gltf: Add some TODOs/FIXMEs to package Orka.glTF.Meshes
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
b2bbfd017ff61957c65fcda970e5e327e0d53110
|
src/core/concurrent/util-concurrent-fifos.adb
|
src/core/concurrent/util-concurrent-fifos.adb
|
-----------------------------------------------------------------------
-- util-concurrent-fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012, 2014, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : constant Element_Array_Access
:= new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
-----------------------------------------------------------------------
-- util-concurrent-fifos -- Concurrent Fifo Queues
-- Copyright (C) 2012, 2014, 2015, 2017, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Concurrent.Fifos is
-- ------------------------------
-- Put the element in the queue.
-- ------------------------------
procedure Enqueue (Into : in out Fifo;
Item : in Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
Into.Buffer.Enqueue (Item);
else
select
Into.Buffer.Enqueue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
procedure Dequeue (From : in out Fifo;
Item : out Element_Type;
Wait : in Duration := FOREVER) is
begin
if Wait < 0.0 then
From.Buffer.Dequeue (Item);
else
select
From.Buffer.Dequeue (Item);
or
delay Wait;
raise Timeout;
end select;
end if;
end Dequeue;
-- ------------------------------
-- Wait for the fifo to become empty.
-- ------------------------------
procedure Wait_Empty (From : in out Fifo) is
begin
From.Buffer.Wait_Empty;
end Wait_Empty;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count (From : in Fifo) return Natural is
begin
return From.Buffer.Get_Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Into : in out Fifo;
Capacity : in Positive) is
begin
Into.Buffer.Set_Size (Capacity);
end Set_Size;
-- ------------------------------
-- Initializes the queue.
-- ------------------------------
overriding
procedure Initialize (Object : in out Fifo) is
begin
Object.Buffer.Set_Size (Default_Size);
end Initialize;
-- ------------------------------
-- Release the queue elements.
-- ------------------------------
overriding
procedure Finalize (Object : in out Fifo) is
begin
if Clear_On_Dequeue then
while Object.Get_Count > 0 loop
declare
Unused : Element_Type;
begin
Object.Dequeue (Unused);
end;
end loop;
end if;
Object.Buffer.Set_Size (0);
end Finalize;
-- Queue of objects.
protected body Protected_Fifo is
-- ------------------------------
-- Put the element in the queue.
-- If the queue is full, wait until some room is available.
-- ------------------------------
entry Enqueue (Item : in Element_Type) when Count < Elements'Length - (if Clear_On_Dequeue then 1 else 0) is
begin
Elements (Last) := Item;
Last := Last + 1;
if Last > Elements'Last then
if Clear_On_Dequeue then
Last := Elements'First + 1;
else
Last := Elements'First;
end if;
end if;
Count := Count + 1;
end Enqueue;
-- ------------------------------
-- Get an element from the queue.
-- Wait until one element gets available.
-- ------------------------------
entry Dequeue (Item : out Element_Type) when Count > 0 is
begin
Count := Count - 1;
Item := Elements (First);
-- For the clear on dequeue mode, erase the queue element.
-- If the element holds some storage or a reference, this gets cleared here.
-- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue
-- is false). There is no overhead when this is not used
-- (ie, instantiation/compile time flag).
if Clear_On_Dequeue then
Elements (First) := Elements (0);
end if;
First := First + 1;
if First > Elements'Last then
if Clear_On_Dequeue then
First := Elements'First + 1;
else
First := Elements'First;
end if;
end if;
end Dequeue;
-- ------------------------------
-- Wait for the queue to become empty.
-- ------------------------------
entry Wait_Empty when Count = 0 is
begin
null;
end Wait_Empty;
-- ------------------------------
-- Get the number of elements in the queue.
-- ------------------------------
function Get_Count return Natural is
begin
return Count;
end Get_Count;
-- ------------------------------
-- Set the queue size.
-- ------------------------------
procedure Set_Size (Capacity : in Natural) is
procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access);
First_Pos : Natural := 1;
begin
if Clear_On_Dequeue then
First_Pos := 0;
end if;
if Capacity = 0 then
Free (Elements);
elsif Elements = null then
Elements := new Element_Array (First_Pos .. Capacity);
else
declare
New_Array : constant Element_Array_Access
:= new Element_Array (First_Pos .. Capacity);
begin
if Capacity > Elements'Length then
New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last);
else
New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity);
end if;
Free (Elements);
Elements := New_Array;
end;
end if;
end Set_Size;
end Protected_Fifo;
end Util.Concurrent.Fifos;
|
Implement Wait_Empty operation and fix Enqueue when Clear_On_Dequeue is used
|
Implement Wait_Empty operation and fix Enqueue when Clear_On_Dequeue is used
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e33e08bec9dc11ad8e2c9f57742a0841318ab38e
|
mat/src/symbols/mat-symbols-targets.ads
|
mat/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Bfd.Symbols;
with Bfd.Files;
package MAT.Symbols.Targets is
type Target_Symbols is limited record
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Bfd.Symbols;
with Bfd.Files;
with MAT.Types;
package MAT.Symbols.Targets is
type Target_Symbols is limited record
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Func : out Ada.Strings.Unbounded.Unbounded_String;
Line : out Natural);
end MAT.Symbols.Targets;
|
Declare the Find_Nearest_Line procedure
|
Declare the Find_Nearest_Line procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
470ec0ac888fa0ef167b1380cacfee977805dddb
|
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;
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);
-- Prepare first byte
This.Periph.TXD.TXD := Data (Data'First);
-- Start TX sequence
This.Periph.TASKS_STARTTX := 1;
loop
loop
if This.Periph.EVENTS_ERROR /= 0 then
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.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;
|
Fix I2C address handling
|
nRF51.TWI: Fix I2C address handling
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
e87c8c1bd4967bf9f0df6cb4933aa0f0288d8b93
|
mat/src/mat-commands.adb
|
mat/src/mat-commands.adb
|
-----------------------------------------------------------------------
-- mat-interp -- Command interpreter
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Log.Loggers;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Bfd;
with MAT.Types;
with MAT.Readers.Files;
with MAT.Memory.Tools;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Expressions;
with MAT.Frames;
with MAT.Consoles;
package body MAT.Commands is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands");
function Get_Command (Line : in String) return String;
procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Frames_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
package Command_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Command_Handler,
Equivalent_Keys => "=",
Hash => Ada.Strings.Hash);
Commands : Command_Map.Map;
-- ------------------------------
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
-- ------------------------------
procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
procedure Print (Addr : in MAT.Types.Target_Addr;
Slot : in MAT.Memory.Allocation);
Slots : MAT.Memory.Allocation_Map;
Iter : MAT.Memory.Allocation_Cursor;
procedure Print (Addr : in MAT.Types.Target_Addr;
Slot : in MAT.Memory.Allocation) is
use type MAT.Frames.Frame_Type;
Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame);
Name : Ada.Strings.Unbounded.Unbounded_String;
Func : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
begin
Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr));
Ada.Text_IO.Set_Col (14);
Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size));
Ada.Text_IO.Set_Col (30);
Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread));
Ada.Text_IO.Set_Col (50);
Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time));
Ada.Text_IO.New_Line;
for I in Backtrace'Range loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Natural'Image (I));
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I)));
MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols,
Addr => Backtrace (I),
Name => Name,
Func => Func,
Line => Line);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func));
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name));
if Line /= 0 then
Ada.Text_IO.Put (":");
Ada.Text_IO.Put (Util.Strings.Image (Line));
end if;
Ada.Text_IO.New_Line;
end loop;
end Print;
Filter : MAT.Expressions.Expression_Type;
begin
Filter := MAT.Expressions.Parse (Args);
Target.Memory.Find (From => MAT.Types.Target_Addr'First,
To => MAT.Types.Target_Addr'Last,
Filter => Filter,
Into => Slots);
Iter := Slots.First;
while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop
MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access);
MAT.Memory.Allocation_Maps.Next (Iter);
end loop;
exception
when E : others =>
Log.Error ("Exception when evaluating " & Args, E);
Target.Console.Error ("Invalid selection");
end Slot_Command;
-- ------------------------------
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
-- ------------------------------
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
pragma Unreferenced (Args);
Sizes : MAT.Memory.Tools.Size_Info_Map;
Iter : MAT.Memory.Tools.Size_Info_Cursor;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25);
Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.End_Title;
MAT.Memory.Targets.Size_Information (Memory => Target.Memory,
Sizes => Sizes);
Iter := Sizes.First;
while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop
declare
use MAT.Memory.Tools;
use type MAT.Types.Target_Size;
Size : constant MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter);
Info : constant Size_Info_Type := Memory.Tools.Size_Info_Maps.Element (Iter);
Total : constant MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count);
begin
Console.Start_Row;
Console.Print_Size (MAT.Consoles.F_SIZE, Size);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count);
Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total);
Console.End_Row;
end;
MAT.Memory.Tools.Size_Info_Maps.Next (Iter);
end loop;
end Sizes_Command;
-- ------------------------------
-- Threads command.
-- Collect statistics about the threads and their allocation.
-- ------------------------------
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
pragma Unreferenced (Args);
Threads : MAT.Memory.Memory_Info_Map;
Iter : MAT.Memory.Memory_Info_Cursor;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_THREAD, "Thread", 10);
Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15);
Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15);
Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15);
Console.End_Title;
MAT.Memory.Targets.Thread_Information (Memory => Target.Memory,
Threads => Threads);
Iter := Threads.First;
while MAT.Memory.Memory_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Thread : constant Types.Target_Thread_Ref := MAT.Memory.Memory_Info_Maps.Key (Iter);
Info : constant Memory.Memory_Info := MAT.Memory.Memory_Info_Maps.Element (Iter);
begin
Console.Start_Row;
Console.Print_Thread (MAT.Consoles.F_THREAD, Thread);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Alloc_Count);
Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Total_Size);
Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Min_Slot_Size);
Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Max_Slot_Size);
Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Min_Addr);
Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Max_Addr);
Console.End_Row;
end;
MAT.Memory.Memory_Info_Maps.Next (Iter);
end loop;
end Threads_Command;
-- ------------------------------
-- Frames command.
-- Collect statistics about the frames and their allocation.
-- ------------------------------
procedure Frames_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Frames : MAT.Memory.Frame_Info_Map;
Iter : MAT.Memory.Frame_Info_Cursor;
Level : Positive := 3;
Console : constant MAT.Consoles.Console_Access := Target.Console;
begin
if Args'Length > 0 then
Level := Positive'Value (Args);
end if;
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_FILE_NAME, "File", 20);
Console.Print_Title (MAT.Consoles.F_FUNCTION_NAME, "Function", 20);
Console.Print_Title (MAT.Consoles.F_LINE_NUMBER, "Line", 6);
Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15);
Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15);
Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15);
Console.End_Title;
MAT.Memory.Targets.Frame_Information (Memory => Target.Memory,
Level => Level,
Frames => Frames);
Iter := Frames.First;
while MAT.Memory.Frame_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Func : constant Types.Target_Addr := MAT.Memory.Frame_Info_Maps.Key (Iter);
Info : constant Memory.Frame_Info := MAT.Memory.Frame_Info_Maps.Element (Iter);
Name : Ada.Strings.Unbounded.Unbounded_String;
File_Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
begin
MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols,
Addr => Func,
Name => Name,
Func => File_Name,
Line => Line);
Console.Start_Row;
Console.Print_Field (MAT.Consoles.F_FILE_NAME, File_Name);
Console.Print_Field (MAT.Consoles.F_FUNCTION_NAME, Name);
Console.Print_Field (MAT.Consoles.F_LINE_NUMBER, Line);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Memory.Alloc_Count);
Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Memory.Total_Size);
Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Memory.Min_Slot_Size);
Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Memory.Max_Slot_Size);
Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Memory.Min_Addr);
Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Memory.Max_Addr);
Console.End_Row;
end;
MAT.Memory.Frame_Info_Maps.Next (Iter);
end loop;
end Frames_Command;
-- ------------------------------
-- Symbol command.
-- Load the symbols from the binary file.
-- ------------------------------
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
begin
MAT.Symbols.Targets.Open (Target.Symbols, Args);
exception
when Bfd.OPEN_ERROR =>
Target.Console.Error ("Cannot open symbol file '" & Args & "'");
end Symbol_Command;
-- ------------------------------
-- Exit command.
-- ------------------------------
procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
begin
raise Stop_Interp;
end Exit_Command;
-- ------------------------------
-- Open a MAT file and read the events.
-- ------------------------------
procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Reader : MAT.Readers.Files.File_Reader_Type;
begin
Target.Initialize (Reader);
Reader.Open (Args);
Reader.Read_All;
exception
when E : Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot open {0}: {1}", Args, Ada.Exceptions.Exception_Message (E));
end Open_Command;
function Get_Command (Line : in String) return String is
Pos : constant Natural := Util.Strings.Index (Line, ' ');
begin
if Pos = 0 then
return Line;
else
return Line (Line'First .. Pos - 1);
end if;
end Get_Command;
-- ------------------------------
-- Execute the command given in the line.
-- ------------------------------
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String) is
Command : constant String := Get_Command (Line);
Index : constant Natural := Util.Strings.Index (Line, ' ');
Pos : constant Command_Map.Cursor := Commands.Find (Command);
begin
if Command_Map.Has_Element (Pos) then
Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last));
elsif Command'Length > 0 then
Target.Console.Error ("Command '" & Command & "' not found");
end if;
exception
when Stop_Interp =>
raise;
when E : others =>
Log.Error ("Exception: ", E);
Target.Console.Error ("Exception while processing command");
end Execute;
begin
Commands.Insert ("exit", Exit_Command'Access);
Commands.Insert ("quit", Exit_Command'Access);
Commands.Insert ("open", Open_Command'Access);
Commands.Insert ("sizes", Sizes_Command'Access);
Commands.Insert ("symbol", Symbol_Command'Access);
Commands.Insert ("slots", Slot_Command'Access);
Commands.Insert ("threads", Threads_Command'Access);
Commands.Insert ("frames", Frames_Command'Access);
end MAT.Commands;
|
-----------------------------------------------------------------------
-- mat-interp -- Command interpreter
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Log.Loggers;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Bfd;
with MAT.Types;
with MAT.Readers.Files;
with MAT.Memory.Tools;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Expressions;
with MAT.Frames;
with MAT.Consoles;
package body MAT.Commands is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands");
function Get_Command (Line : in String) return String;
procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Frames_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
package Command_Map is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => Command_Handler,
Equivalent_Keys => "=",
Hash => Ada.Strings.Hash);
Commands : Command_Map.Map;
-- ------------------------------
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
-- ------------------------------
procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
procedure Print (Addr : in MAT.Types.Target_Addr;
Slot : in MAT.Memory.Allocation);
Slots : MAT.Memory.Allocation_Map;
Iter : MAT.Memory.Allocation_Cursor;
procedure Print (Addr : in MAT.Types.Target_Addr;
Slot : in MAT.Memory.Allocation) is
use type MAT.Frames.Frame_Type;
Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame);
Name : Ada.Strings.Unbounded.Unbounded_String;
Func : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
begin
Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr));
Ada.Text_IO.Set_Col (14);
Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size));
Ada.Text_IO.Set_Col (30);
Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread));
Ada.Text_IO.Set_Col (50);
Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time));
Ada.Text_IO.New_Line;
for I in Backtrace'Range loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Natural'Image (I));
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I)));
MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols,
Addr => Backtrace (I),
Name => Name,
Func => Func,
Line => Line);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func));
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name));
if Line /= 0 then
Ada.Text_IO.Put (":");
Ada.Text_IO.Put (Util.Strings.Image (Line));
end if;
Ada.Text_IO.New_Line;
end loop;
end Print;
Filter : MAT.Expressions.Expression_Type;
Process : constant MAT.Targets.Target_Process_Type_Access := Target.Process;
begin
Filter := MAT.Expressions.Parse (Args);
Process.Memory.Find (From => MAT.Types.Target_Addr'First,
To => MAT.Types.Target_Addr'Last,
Filter => Filter,
Into => Slots);
Iter := Slots.First;
while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop
MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access);
MAT.Memory.Allocation_Maps.Next (Iter);
end loop;
exception
when E : others =>
Log.Error ("Exception when evaluating " & Args, E);
Target.Console.Error ("Invalid selection");
end Slot_Command;
-- ------------------------------
-- Sizes command.
-- Collect statistics about the used memory slots and report the different slot
-- sizes with count.
-- ------------------------------
procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
pragma Unreferenced (Args);
Sizes : MAT.Memory.Tools.Size_Info_Map;
Iter : MAT.Memory.Tools.Size_Info_Cursor;
Console : constant MAT.Consoles.Console_Access := Target.Console;
Process : constant MAT.Targets.Target_Process_Type_Access := Target.Process;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25);
Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.End_Title;
MAT.Memory.Targets.Size_Information (Memory => Process.Memory,
Sizes => Sizes);
Iter := Sizes.First;
while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop
declare
use MAT.Memory.Tools;
use type MAT.Types.Target_Size;
Size : constant MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter);
Info : constant Size_Info_Type := Memory.Tools.Size_Info_Maps.Element (Iter);
Total : constant MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count);
begin
Console.Start_Row;
Console.Print_Size (MAT.Consoles.F_SIZE, Size);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count);
Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total);
Console.End_Row;
end;
MAT.Memory.Tools.Size_Info_Maps.Next (Iter);
end loop;
end Sizes_Command;
-- ------------------------------
-- Threads command.
-- Collect statistics about the threads and their allocation.
-- ------------------------------
procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
pragma Unreferenced (Args);
Threads : MAT.Memory.Memory_Info_Map;
Iter : MAT.Memory.Memory_Info_Cursor;
Console : constant MAT.Consoles.Console_Access := Target.Console;
Process : constant MAT.Targets.Target_Process_Type_Access := Target.Process;
begin
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_THREAD, "Thread", 10);
Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15);
Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15);
Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15);
Console.End_Title;
MAT.Memory.Targets.Thread_Information (Memory => Process.Memory,
Threads => Threads);
Iter := Threads.First;
while MAT.Memory.Memory_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Thread : constant Types.Target_Thread_Ref := MAT.Memory.Memory_Info_Maps.Key (Iter);
Info : constant Memory.Memory_Info := MAT.Memory.Memory_Info_Maps.Element (Iter);
begin
Console.Start_Row;
Console.Print_Thread (MAT.Consoles.F_THREAD, Thread);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Alloc_Count);
Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Total_Size);
Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Min_Slot_Size);
Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Max_Slot_Size);
Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Min_Addr);
Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Max_Addr);
Console.End_Row;
end;
MAT.Memory.Memory_Info_Maps.Next (Iter);
end loop;
end Threads_Command;
-- ------------------------------
-- Frames command.
-- Collect statistics about the frames and their allocation.
-- ------------------------------
procedure Frames_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Frames : MAT.Memory.Frame_Info_Map;
Iter : MAT.Memory.Frame_Info_Cursor;
Level : Positive := 3;
Console : constant MAT.Consoles.Console_Access := Target.Console;
Process : constant MAT.Targets.Target_Process_Type_Access := Target.Process;
begin
if Args'Length > 0 then
Level := Positive'Value (Args);
end if;
Console.Start_Title;
Console.Print_Title (MAT.Consoles.F_FILE_NAME, "File", 20);
Console.Print_Title (MAT.Consoles.F_FUNCTION_NAME, "Function", 20);
Console.Print_Title (MAT.Consoles.F_LINE_NUMBER, "Line", 6);
Console.Print_Title (MAT.Consoles.F_COUNT, "# Allocation", 12);
Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_SIZE, "Min slot size", 15);
Console.Print_Title (MAT.Consoles.F_MAX_SIZE, "Max slot size", 15);
Console.Print_Title (MAT.Consoles.F_MIN_ADDR, "Low address", 15);
Console.Print_Title (MAT.Consoles.F_MAX_ADDR, "High address", 15);
Console.End_Title;
MAT.Memory.Targets.Frame_Information (Memory => Process.Memory,
Level => Level,
Frames => Frames);
Iter := Frames.First;
while MAT.Memory.Frame_Info_Maps.Has_Element (Iter) loop
declare
use type MAT.Types.Target_Size;
Func : constant Types.Target_Addr := MAT.Memory.Frame_Info_Maps.Key (Iter);
Info : constant Memory.Frame_Info := MAT.Memory.Frame_Info_Maps.Element (Iter);
Name : Ada.Strings.Unbounded.Unbounded_String;
File_Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
begin
MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols,
Addr => Func,
Name => Name,
Func => File_Name,
Line => Line);
Console.Start_Row;
Console.Print_Field (MAT.Consoles.F_FILE_NAME, File_Name);
Console.Print_Field (MAT.Consoles.F_FUNCTION_NAME, Name);
Console.Print_Field (MAT.Consoles.F_LINE_NUMBER, Line);
Console.Print_Field (MAT.Consoles.F_COUNT, Info.Memory.Alloc_Count);
Console.Print_Size (MAT.Consoles.F_TOTAL_SIZE, Info.Memory.Total_Size);
Console.Print_Size (MAT.Consoles.F_MIN_SIZE, Info.Memory.Min_Slot_Size);
Console.Print_Size (MAT.Consoles.F_MAX_SIZE, Info.Memory.Max_Slot_Size);
Console.Print_Field (MAT.Consoles.F_MIN_ADDR, Info.Memory.Min_Addr);
Console.Print_Field (MAT.Consoles.F_MAX_ADDR, Info.Memory.Max_Addr);
Console.End_Row;
end;
MAT.Memory.Frame_Info_Maps.Next (Iter);
end loop;
end Frames_Command;
-- ------------------------------
-- Symbol command.
-- Load the symbols from the binary file.
-- ------------------------------
procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
begin
MAT.Symbols.Targets.Open (Target.Symbols, Args);
exception
when Bfd.OPEN_ERROR =>
Target.Console.Error ("Cannot open symbol file '" & Args & "'");
end Symbol_Command;
-- ------------------------------
-- Exit command.
-- ------------------------------
procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
begin
raise Stop_Interp;
end Exit_Command;
-- ------------------------------
-- Open a MAT file and read the events.
-- ------------------------------
procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class;
Args : in String) is
Reader : MAT.Readers.Files.File_Reader_Type;
begin
Target.Initialize (Reader);
Reader.Open (Args);
Reader.Read_All;
exception
when E : Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot open {0}: {1}", Args, Ada.Exceptions.Exception_Message (E));
end Open_Command;
function Get_Command (Line : in String) return String is
Pos : constant Natural := Util.Strings.Index (Line, ' ');
begin
if Pos = 0 then
return Line;
else
return Line (Line'First .. Pos - 1);
end if;
end Get_Command;
-- ------------------------------
-- Execute the command given in the line.
-- ------------------------------
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String) is
Command : constant String := Get_Command (Line);
Index : constant Natural := Util.Strings.Index (Line, ' ');
Pos : constant Command_Map.Cursor := Commands.Find (Command);
begin
if Command_Map.Has_Element (Pos) then
Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last));
elsif Command'Length > 0 then
Target.Console.Error ("Command '" & Command & "' not found");
end if;
exception
when Stop_Interp =>
raise;
when E : others =>
Log.Error ("Exception: ", E);
Target.Console.Error ("Exception while processing command");
end Execute;
begin
Commands.Insert ("exit", Exit_Command'Access);
Commands.Insert ("quit", Exit_Command'Access);
Commands.Insert ("open", Open_Command'Access);
Commands.Insert ("sizes", Sizes_Command'Access);
Commands.Insert ("symbol", Symbol_Command'Access);
Commands.Insert ("slots", Slot_Command'Access);
Commands.Insert ("threads", Threads_Command'Access);
Commands.Insert ("frames", Frames_Command'Access);
end MAT.Commands;
|
Use the Process function to get the target process instance
|
Use the Process function to get the target process instance
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
15cfff19266692d3ddcae3a82a990b0d4580245b
|
mat/src/mat-consoles.adb
|
mat/src/mat-consoles.adb
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Consoles is
-- ------------------------------
-- Format the address and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr) is
Value : constant String := MAT.Types.Hex_Image (Addr);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Field;
-- ------------------------------
-- Format the size and print it for the given field.
-- ------------------------------
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size) is
Value : constant String := MAT.Types.Target_Size'Image (Size);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Size;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer) is
Val : constant String := Integer'Image (Value);
begin
Console_Type'Class (Console).Print_Field (Field, Val);
end Print_Field;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Consoles is
-- ------------------------------
-- Print the title for the given field and setup the associated field size.
-- ------------------------------
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive) is
begin
Console.Sizes (Field) := Length;
Console.Field_Count := Console.Field_Count + 1;
Console.Fields (Console.Field_Count) := Field;
Console_Type'Class (Console).Print_Title (Field, Title);
end Print_Title;
-- ------------------------------
-- Format the address and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr) is
Value : constant String := MAT.Types.Hex_Image (Addr);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Field;
-- ------------------------------
-- Format the size and print it for the given field.
-- ------------------------------
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size) is
Value : constant String := MAT.Types.Target_Size'Image (Size);
begin
Console_Type'Class (Console).Print_Field (Field, Value);
end Print_Size;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer) is
Val : constant String := Integer'Image (Value);
begin
Console_Type'Class (Console).Print_Field (Field, Val);
end Print_Field;
end MAT.Consoles;
|
Implement the Print_Title procedure to keep track of column sizes
|
Implement the Print_Title procedure to keep track of column sizes
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
3e70f590542546c57a89dde5c35d5397c6bf6658
|
src/sys/streams/util-streams-buffered.adb
|
src/sys/streams/util-streams-buffered.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
package body Util.Streams.Buffered is
procedure Free_Buffer is
new Ada.Unchecked_Deallocation (Object => Stream_Element_Array,
Name => Buffer_Access);
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : in Output_Stream_Access;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Output := Output;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
Stream.No_Flush := False;
end Initialize;
-- ------------------------------
-- Initialize the stream to read from the string.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Content'Length);
Stream.Buffer := new Stream_Element_Array (1 .. Content'Length);
Stream.Input := null;
Stream.Write_Pos := Stream.Last + 1;
Stream.Read_Pos := 1;
for I in Content'Range loop
Stream.Buffer (Stream_Element_Offset (I - Content'First + 1))
:= Character'Pos (Content (I));
end loop;
end Initialize;
-- ------------------------------
-- Initialize the stream with a buffer of <b>Size</b> bytes.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive) is
begin
Stream.Initialize (Output => null, Size => Size);
Stream.No_Flush := True;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : in Input_Stream_Access;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Close the sink.
-- ------------------------------
overriding
procedure Close (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Output /= null then
Output_Buffer_Stream'Class (Stream).Flush;
Stream.Output.Close;
end if;
end Close;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is
begin
return Stream.Buffer;
end Get_Buffer;
-- ------------------------------
-- Get the number of element in the stream.
-- ------------------------------
function Get_Size (Stream : in Output_Buffer_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Start : Stream_Element_Offset := Buffer'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
begin
while Start <= Buffer'Last loop
Size := Buffer'Last - Start + 1;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Pos := 1;
Avail := Stream.Last - Pos + 1;
end if;
if Avail < Size then
Size := Avail;
end if;
Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Stream.Write_Pos := Pos;
-- If we have still more data than the buffer size, flush and write
-- the buffer directly.
if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
overriding
procedure Flush (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Write_Pos > 1 and not Stream.No_Flush then
if Stream.Output /= null then
Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1));
Stream.Output.Flush;
end if;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
if Stream.Write_Pos > 1 then
Into (Into'First .. Into'First + Stream.Write_Pos - 1) :=
Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1);
Stream.Write_Pos := 1;
Last := Into'First + Stream.Write_Pos - 1;
else
Last := Into'First - 1;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer stream to the unbounded string.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Ada.Strings.Unbounded.Set_Unbounded_String (Into, "");
if Stream.Write_Pos > 1 then
for I in 1 .. Stream.Write_Pos - 1 loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I)));
end loop;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
-- ------------------------------
procedure Fill (Stream : in out Input_Buffer_Stream) is
begin
if Stream.Input = null then
Stream.Eof := True;
else
Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos);
Stream.Eof := Stream.Write_Pos < 1;
if not Stream.Eof then
Stream.Write_Pos := Stream.Write_Pos + 1;
end if;
Stream.Read_Pos := 1;
end if;
end Fill;
-- ------------------------------
-- Read one character from the input stream.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character) is
begin
if Stream.Read_Pos >= Stream.Write_Pos then
Stream.Fill;
if Stream.Eof then
raise Ada.IO_Exceptions.Data_Error with "End of buffer";
end if;
end if;
Char := Character'Val (Stream.Buffer (Stream.Read_Pos));
Stream.Read_Pos := Stream.Read_Pos + 1;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Start : Stream_Element_Offset := Into'First;
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
Total : Stream_Element_Offset := 0;
begin
while Start <= Into'Last loop
Size := Into'Last - Start + 1;
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
exit when Avail <= 0;
end if;
if Avail < Size then
Size := Avail;
end if;
Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Total := Total + Size;
Stream.Read_Pos := Pos;
end loop;
Last := Total;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String) is
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
begin
loop
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
if Stream.Eof then
return;
end if;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
end if;
for I in 1 .. Avail loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos)));
Pos := Pos + 1;
end loop;
Stream.Read_Pos := Pos;
end loop;
end Read;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Output_Buffer_Stream) is
begin
if Object.Buffer /= null then
if Object.Output /= null then
Object.Flush;
end if;
Free_Buffer (Object.Buffer);
end if;
end Finalize;
-- ------------------------------
-- Returns True if the end of the stream is reached.
-- ------------------------------
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is
begin
return Stream.Eof;
end Is_Eof;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Input_Buffer_Stream) is
begin
if Object.Buffer /= null then
Free_Buffer (Object.Buffer);
end if;
end Finalize;
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Unchecked_Deallocation;
package body Util.Streams.Buffered is
procedure Free_Buffer is
new Ada.Unchecked_Deallocation (Object => Stream_Element_Array,
Name => Buffer_Access);
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : access Output_Stream'Class;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Output := Output;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
Stream.No_Flush := False;
end Initialize;
-- ------------------------------
-- Initialize the stream to read from the string.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Content'Length);
Stream.Buffer := new Stream_Element_Array (1 .. Content'Length);
Stream.Input := null;
Stream.Write_Pos := Stream.Last + 1;
Stream.Read_Pos := 1;
for I in Content'Range loop
Stream.Buffer (Stream_Element_Offset (I - Content'First + 1))
:= Character'Pos (Content (I));
end loop;
end Initialize;
-- ------------------------------
-- Initialize the stream with a buffer of <b>Size</b> bytes.
-- ------------------------------
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive) is
begin
Stream.Initialize (Output => null, Size => Size);
Stream.No_Flush := True;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Initialize the stream to read or write on the given streams.
-- An internal buffer is allocated for writing the stream.
-- ------------------------------
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : access Input_Stream'Class;
Size : in Positive) is
begin
Free_Buffer (Stream.Buffer);
Stream.Last := Stream_Element_Offset (Size);
Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last);
Stream.Input := Input;
Stream.Write_Pos := 1;
Stream.Read_Pos := 1;
end Initialize;
-- ------------------------------
-- Close the sink.
-- ------------------------------
overriding
procedure Close (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Output /= null then
Output_Buffer_Stream'Class (Stream).Flush;
Stream.Output.Close;
end if;
end Close;
-- ------------------------------
-- Get the direct access to the buffer.
-- ------------------------------
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is
begin
return Stream.Buffer;
end Get_Buffer;
-- ------------------------------
-- Get the number of element in the stream.
-- ------------------------------
function Get_Size (Stream : in Output_Buffer_Stream) return Natural is
begin
return Natural (Stream.Write_Pos - Stream.Read_Pos);
end Get_Size;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Start : Stream_Element_Offset := Buffer'First;
Pos : Stream_Element_Offset := Stream.Write_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
begin
while Start <= Buffer'Last loop
Size := Buffer'Last - Start + 1;
Avail := Stream.Last - Pos + 1;
if Avail = 0 then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Pos := 1;
Avail := Stream.Last - Pos + 1;
end if;
if Avail < Size then
Size := Avail;
end if;
Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Stream.Write_Pos := Pos;
-- If we have still more data than the buffer size, flush and write
-- the buffer directly.
if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then
if Stream.Output = null then
raise Ada.IO_Exceptions.End_Error with "Buffer is full";
end if;
Stream.Output.Write (Stream.Buffer (1 .. Pos - 1));
Stream.Write_Pos := 1;
Stream.Output.Write (Buffer (Start .. Buffer'Last));
return;
end if;
end loop;
end Write;
-- ------------------------------
-- Flush the stream.
-- ------------------------------
overriding
procedure Flush (Stream : in out Output_Buffer_Stream) is
begin
if Stream.Write_Pos > 1 and not Stream.No_Flush then
if Stream.Output /= null then
Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1));
Stream.Output.Flush;
end if;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
if Stream.Write_Pos > 1 then
Into (Into'First .. Into'First + Stream.Write_Pos - 1) :=
Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1);
Stream.Write_Pos := 1;
Last := Into'First + Stream.Write_Pos - 1;
else
Last := Into'First - 1;
end if;
end Flush;
-- ------------------------------
-- Flush the buffer stream to the unbounded string.
-- ------------------------------
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Ada.Strings.Unbounded.Set_Unbounded_String (Into, "");
if Stream.Write_Pos > 1 then
for I in 1 .. Stream.Write_Pos - 1 loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I)));
end loop;
Stream.Write_Pos := 1;
end if;
end Flush;
-- ------------------------------
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
-- ------------------------------
procedure Fill (Stream : in out Input_Buffer_Stream) is
begin
if Stream.Input = null then
Stream.Eof := True;
else
Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos);
Stream.Eof := Stream.Write_Pos < 1;
if not Stream.Eof then
Stream.Write_Pos := Stream.Write_Pos + 1;
end if;
Stream.Read_Pos := 1;
end if;
end Fill;
-- ------------------------------
-- Read one character from the input stream.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character) is
begin
if Stream.Read_Pos >= Stream.Write_Pos then
Stream.Fill;
if Stream.Eof then
raise Ada.IO_Exceptions.Data_Error with "End of buffer";
end if;
end if;
Char := Character'Val (Stream.Buffer (Stream.Read_Pos));
Stream.Read_Pos := Stream.Read_Pos + 1;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Start : Stream_Element_Offset := Into'First;
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
Size : Stream_Element_Offset;
Total : Stream_Element_Offset := 0;
begin
while Start <= Into'Last loop
Size := Into'Last - Start + 1;
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
exit when Avail <= 0;
end if;
if Avail < Size then
Size := Avail;
end if;
Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1);
Start := Start + Size;
Pos := Pos + Size;
Total := Total + Size;
Stream.Read_Pos := Pos;
end loop;
Last := Total;
end Read;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String) is
Pos : Stream_Element_Offset := Stream.Read_Pos;
Avail : Stream_Element_Offset;
begin
loop
Avail := Stream.Write_Pos - Pos;
if Avail = 0 then
Stream.Fill;
if Stream.Eof then
return;
end if;
Pos := Stream.Read_Pos;
Avail := Stream.Write_Pos - Pos;
end if;
for I in 1 .. Avail loop
Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos)));
Pos := Pos + 1;
end loop;
Stream.Read_Pos := Pos;
end loop;
end Read;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Output_Buffer_Stream) is
begin
if Object.Buffer /= null then
if Object.Output /= null then
Object.Flush;
end if;
Free_Buffer (Object.Buffer);
end if;
end Finalize;
-- ------------------------------
-- Returns True if the end of the stream is reached.
-- ------------------------------
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is
begin
return Stream.Eof;
end Is_Eof;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out Input_Buffer_Stream) is
begin
if Object.Buffer /= null then
Free_Buffer (Object.Buffer);
end if;
end Finalize;
end Util.Streams.Buffered;
|
Use anonymous access type for the input and output streams
|
Use anonymous access type for the input and output streams
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1fd26820dfe2cbd5589309c1e35c1d5576b735fa
|
matp/src/events/mat-events-targets.adb
|
matp/src/events/mat-events-targets.adb
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body MAT.Events.Targets is
ITERATE_COUNT : constant Event_Id_Type := 10_000;
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in out Target_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Target : in out Target_Events;
Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
begin
Target.Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out MAT.Events.Tools.Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (Target : in out Target_Events;
First : out Target_Event_Type;
Last : out Target_Event_Type) is
begin
Target.Events.Get_Limits (First, Last);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Target_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Target_Event_Type)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
-- ------------------------------
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event_Type)) is
First_Event : Target_Event_Type;
Last_Event : Target_Event_Type;
First_Id : Event_Id_Type;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
-- Iterate over the events in groups of 10_000 to release the lock and give some
-- opportunity to the server thread to add new events.
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Process);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Iterate;
-- ------------------------------
-- Release the storage allocated for the events.
-- ------------------------------
overriding
procedure Finalize (Target : in out Target_Events) is
begin
Target.Events.Clear;
end Finalize;
protected body Event_Collector is
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Target_Event_Type));
-- ------------------------------
-- Internal operation to update the event represented by <tt>Id</tt>.
-- ------------------------------
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Target_Event_Type)) is
Iter : constant Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
if Event_Id_Maps.Has_Element (Iter) then
Block := Event_Id_Maps.Element (Iter);
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
Process (Block.Events (Pos));
end if;
end if;
end Update;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
procedure Update_Size (Event : in out Target_Event_Type);
procedure Update_Next (Event : in out Target_Event_Type);
procedure Update_Size (Event : in out Target_Event_Type) is
begin
Event.Size := Size;
Event.Prev_Id := Prev_Id;
end Update_Size;
procedure Update_Next (Event : in out Target_Event_Type) is
begin
Event.Next_Id := Id;
end Update_Next;
begin
Update (Id, Update_Size'Access);
Update (Prev_Id, Update_Next'Access);
end Update_Event;
-- ------------------------------
-- Add the event in the list of events.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Event : in out Target_Event_Type) is
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id, Current);
end if;
Event.Id := Last_Id;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out MAT.Events.Tools.Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (First : out Target_Event_Type;
Last : out Target_Event_Type) is
First_Block : constant Event_Block_Access := Events.First_Element;
Last_Block : constant Event_Block_Access := Events.Last_Element;
begin
First := First_Block.Events (First_Block.Events'First);
Last := Last_Block.Events (Last_Block.Count);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Target_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise MAT.Events.Tools.Not_Found;
end Get_Event;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Target_Event_Type)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Start <= Finish then
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos > Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
else
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id <= Finish;
Id := Id - 1;
if Pos = Block.Events'First then
Event_Id_Maps.Previous (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Count;
else
Pos := Pos - 1;
end if;
end loop;
end if;
Event_Id_Maps.Previous (Iter);
end if;
end loop;
end Iterate;
-- ------------------------------
-- Clear the events.
-- ------------------------------
procedure Clear is
procedure Free is
new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access);
begin
while not Events.Is_Empty loop
declare
Block : Event_Block_Access := Events.First_Element;
begin
Free (Block);
Events.Delete_First;
end;
end loop;
Current := null;
Last_Id := 0;
Ids.Clear;
end Clear;
end Event_Collector;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body MAT.Events.Targets is
ITERATE_COUNT : constant Event_Id_Type := 10_000;
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in out Target_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Target : in out Target_Events;
Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
begin
Target.Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out MAT.Events.Tools.Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (Target : in out Target_Events;
First : out Target_Event_Type;
Last : out Target_Event_Type) is
begin
Target.Events.Get_Limits (First, Last);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Target_Event_Type is
begin
return Target.Events.Get_Event (Id);
end Get_Event;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Target_Event_Type)) is
begin
Target.Events.Iterate (Start, Finish, Process);
end Iterate;
-- ------------------------------
-- Iterate over the events starting from first first event up to the last event collected.
-- Execute the <tt>Process</tt> procedure with each event instance.
-- ------------------------------
procedure Iterate (Target : in out Target_Events;
Process : access procedure (Event : in Target_Event_Type)) is
First_Event : Target_Event_Type;
Last_Event : Target_Event_Type;
First_Id : Event_Id_Type;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
-- Iterate over the events in groups of 10_000 to release the lock and give some
-- opportunity to the server thread to add new events.
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Process);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Iterate;
-- ------------------------------
-- Release the storage allocated for the events.
-- ------------------------------
overriding
procedure Finalize (Target : in out Target_Events) is
begin
Target.Events.Clear;
end Finalize;
protected body Event_Collector is
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Target_Event_Type));
-- ------------------------------
-- Internal operation to update the event represented by <tt>Id</tt>.
-- ------------------------------
procedure Update (Id : in Event_Id_Type;
Process : not null access procedure (Event : in out Target_Event_Type)) is
Iter : constant Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
if Event_Id_Maps.Has_Element (Iter) then
Block := Event_Id_Maps.Element (Iter);
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
Process (Block.Events (Pos));
end if;
end if;
end Update;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Id : in Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in Event_Id_Type) is
procedure Update_Size (Event : in out Target_Event_Type);
procedure Update_Next (Event : in out Target_Event_Type);
procedure Update_Size (Event : in out Target_Event_Type) is
begin
if Event.Index = MSG_REALLOC then
Event.Old_Size := Size;
else
Event.Size := Size;
end if;
Event.Prev_Id := Prev_Id;
end Update_Size;
procedure Update_Next (Event : in out Target_Event_Type) is
begin
Event.Next_Id := Id;
end Update_Next;
begin
Update (Id, Update_Size'Access);
Update (Prev_Id, Update_Next'Access);
end Update_Event;
-- ------------------------------
-- Add the event in the list of events.
-- Update the event instance to allocate the event Id.
-- ------------------------------
procedure Insert (Event : in out Target_Event_Type) is
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id, Current);
end if;
Event.Id := Last_Id;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out MAT.Events.Tools.Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the first and last event that have been received.
-- ------------------------------
procedure Get_Limits (First : out Target_Event_Type;
Last : out Target_Event_Type) is
First_Block : constant Event_Block_Access := Events.First_Element;
Last_Block : constant Event_Block_Access := Events.Last_Element;
begin
First := First_Block.Events (First_Block.Events'First);
Last := Last_Block.Events (Last_Block.Count);
end Get_Limits;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Target_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Pos <= Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise MAT.Events.Tools.Not_Found;
end Get_Event;
-- ------------------------------
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
-- ------------------------------
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Target_Event_Type)) is
Iter : Event_Id_Cursor := Ids.Floor (Start);
Block : Event_Block_Access;
Pos : Event_Id_Type;
Id : Event_Id_Type := Start;
begin
-- First, find the block and position of the first event.
while Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First;
if Start <= Finish then
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id > Finish;
Pos := Pos + 1;
Id := Id + 1;
if Pos > Block.Count then
Event_Id_Maps.Next (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Events'First;
end if;
end loop;
end if;
Event_Id_Maps.Next (Iter);
else
if Pos <= Block.Count then
-- Second, iterate over the events moving to the next event block
-- until we reach the last event.
loop
Process (Block.Events (Pos));
exit when Id <= Finish;
Id := Id - 1;
if Pos = Block.Events'First then
Event_Id_Maps.Previous (Iter);
exit when not Event_Id_Maps.Has_Element (Iter);
Block := Event_Id_Maps.Element (Iter);
Pos := Block.Count;
else
Pos := Pos - 1;
end if;
end loop;
end if;
Event_Id_Maps.Previous (Iter);
end if;
end loop;
end Iterate;
-- ------------------------------
-- Clear the events.
-- ------------------------------
procedure Clear is
procedure Free is
new Ada.Unchecked_Deallocation (Event_Block, Event_Block_Access);
begin
while not Events.Is_Empty loop
declare
Block : Event_Block_Access := Events.First_Element;
begin
Free (Block);
Events.Delete_First;
end;
end loop;
Current := null;
Last_Id := 0;
Ids.Clear;
end Clear;
end Event_Collector;
end MAT.Events.Targets;
|
Fix the Update_Event procedure to update the Old_Size information if the event type is a MSG_REALLOC
|
Fix the Update_Event procedure to update the Old_Size information if the event type is a MSG_REALLOC
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
7ebfb6d369c109eb681eb6b15a42ed8eb4abc581
|
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
|
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-modules-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with ASF.Contexts.Faces;
with ASF.Contexts.Faces.Mockup;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Votes.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Delete_Question",
Test_Delete_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean",
Test_Question_Vote'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)",
Test_Question_Vote'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Module;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test deletion of a question.
-- ------------------------------
procedure Test_Delete_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Module;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I search strings in Ada?");
Q.Set_Description ("I have two strings that I want to search. % does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
T.Manager.Delete_Question (Q);
end Test_Delete_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
-- ------------------------------
-- Do a vote on a question through the question vote bean.
-- ------------------------------
procedure Do_Vote (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Vote : AWA.Votes.Beans.Vote_Bean_Access;
begin
Context.Set_Parameter ("id", "1");
Bean := Context.Get_Bean ("questionVote");
T.Assert (Bean /= null, "The questionVote bean was not created");
T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class,
"The questionVote is not a Vote_Bean");
Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access;
Vote.Rating := 1;
Vote.Entity_Id := 1;
Vote.Vote_Up (Outcome);
end Do_Vote;
-- ------------------------------
-- Test anonymous user voting for a question.
-- ------------------------------
procedure Test_Question_Vote_Anonymous (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Do_Vote (T);
T.Fail ("Anonymous users should not be allowed to vote");
exception
when AWA.Permissions.NO_PERMISSION =>
null;
end Test_Question_Vote_Anonymous;
-- ------------------------------
-- Test voting for a question.
-- ------------------------------
procedure Test_Question_Vote (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Do_Vote (T);
end Test_Question_Vote;
end AWA.Questions.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-modules-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Security.Contexts;
with ASF.Contexts.Faces;
with ASF.Contexts.Faces.Mockup;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Votes.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Delete_Question",
Test_Delete_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean",
Test_Question_Vote'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)",
Test_Question_Vote'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Module;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test deletion of a question.
-- ------------------------------
procedure Test_Delete_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Module;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I search strings in Ada?");
Q.Set_Description ("I have two strings that I want to search. % does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
T.Manager.Delete_Question (Q);
end Test_Delete_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
-- ------------------------------
-- Do a vote on a question through the question vote bean.
-- ------------------------------
procedure Do_Vote (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Vote : AWA.Votes.Beans.Vote_Bean_Access;
begin
Context.Set_Parameter ("id", "1");
Bean := Context.Get_Bean ("questionVote");
T.Assert (Bean /= null, "The questionVote bean was not created");
T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class,
"The questionVote is not a Vote_Bean");
Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access;
Vote.Rating := 1;
Vote.Entity_Id := 1;
Vote.Vote_Up (Outcome);
end Do_Vote;
-- ------------------------------
-- Test anonymous user voting for a question.
-- ------------------------------
procedure Test_Question_Vote_Anonymous (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Do_Vote (T);
T.Fail ("Anonymous users should not be allowed to vote");
exception
when AWA.Permissions.NO_PERMISSION =>
null;
end Test_Question_Vote_Anonymous;
-- ------------------------------
-- Test voting for a question.
-- ------------------------------
procedure Test_Question_Vote (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Do_Vote (T);
end Test_Question_Vote;
end AWA.Questions.Modules.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
438e345583a502d41e326607c3ebb35811062820
|
boards/stm32_common/dma2d/stm32-dma2d_bitmap.adb
|
boards/stm32_common/dma2d/stm32-dma2d_bitmap.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-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 Ada.Unchecked_Conversion;
with Cortex_M.Cache; use Cortex_M.Cache;
with STM32.DMA2D; use STM32.DMA2D;
package body STM32.DMA2D_Bitmap is
function To_DMA2D_CM is new Ada.Unchecked_Conversion
(HAL.Bitmap.Bitmap_Color_Mode, STM32.DMA2D.DMA2D_Color_Mode);
function To_DMA2D_Color is new Ada.Unchecked_Conversion
(HAL.Bitmap.Bitmap_Color, STM32.DMA2D.DMA2D_Color);
---------------------
-- To_DMA2D_Buffer --
---------------------
function To_DMA2D_Buffer
(Buffer : HAL.Bitmap.Bitmap_Buffer'Class) return DMA2D_Buffer
is
Color_Mode : constant DMA2D_Color_Mode :=
To_DMA2D_CM (Buffer.Color_Mode);
Ret : DMA2D_Buffer (Color_Mode);
begin
Ret.Addr := Buffer.Addr;
Ret.Width := (if Buffer.Swapped then Buffer.Height
else Buffer.Width);
Ret.Height := (if Buffer.Swapped then Buffer.Width
else Buffer.Height);
return Ret;
end To_DMA2D_Buffer;
---------------
-- Set_Pixel --
---------------
overriding procedure Set_Pixel
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural;
Value : UInt32)
is
begin
DMA2D_Wait_Transfer;
HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel (X, Y, Value);
end Set_Pixel;
---------------------
-- Set_Pixel_Blend --
---------------------
overriding procedure Set_Pixel_Blend
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural;
Value : HAL.Bitmap.Bitmap_Color)
is
DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer);
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
if not Buffer.Swapped then
DMA2D_Set_Pixel_Blend
(Buffer => DMA_Buf,
X => X,
Y => Y,
Color => To_DMA2D_Color (Value));
else
DMA2D_Set_Pixel_Blend
(Buffer => DMA_Buf,
X => Y,
Y => Buffer.Width - X - 1,
Color => To_DMA2D_Color (Value));
end if;
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel_Blend (X, Y, Value);
end if;
end Set_Pixel_Blend;
---------------
-- Get_Pixel --
---------------
overriding function Get_Pixel
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural) return UInt32
is
begin
DMA2D_Wait_Transfer;
return HAL.Bitmap.Bitmap_Buffer (Buffer).Get_Pixel (X, Y);
end Get_Pixel;
----------
-- Fill --
----------
overriding procedure Fill
(Buffer : DMA2D_Bitmap_Buffer;
Color : UInt32)
is
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
DMA2D_Fill (To_DMA2D_Buffer (Buffer), Color, True);
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Fill (Color);
end if;
end Fill;
---------------
-- Fill_Rect --
---------------
overriding procedure Fill_Rect
(Buffer : DMA2D_Bitmap_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer)
is
DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer);
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
if not Buffer.Swapped then
DMA2D_Fill_Rect
(DMA_Buf,
Color => Color,
X => X,
Y => Y,
Width => Width,
Height => Height);
else
DMA2D_Fill_Rect
(DMA_Buf,
Color => Color,
X => Y,
Y => Buffer.Width - X - Width,
Width => Height,
Height => Width);
end if;
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Fill_Rect
(Color, X, Y, Width, Height);
end if;
end Fill_Rect;
---------------
-- Copy_Rect --
---------------
overriding procedure Copy_Rect
(Src_Buffer : HAL.Bitmap.Bitmap_Buffer'Class;
X_Src : Natural;
Y_Src : Natural;
Dst_Buffer : DMA2D_Bitmap_Buffer;
X_Dst : Natural;
Y_Dst : Natural;
Bg_Buffer : HAL.Bitmap.Bitmap_Buffer'Class;
X_Bg : Natural;
Y_Bg : Natural;
Width : Natural;
Height : Natural;
Synchronous : Boolean)
is
use type System.Address;
DMA_Buf_Src : constant DMA2D_Buffer := To_DMA2D_Buffer (Src_Buffer);
DMA_Buf_Dst : constant DMA2D_Buffer := To_DMA2D_Buffer (Dst_Buffer);
DMA_Buf_Bg : DMA2D_Buffer := To_DMA2D_Buffer (Bg_Buffer);
X0_Src : Natural := X_Src;
Y0_Src : Natural := Y_Src;
X0_Dst : Natural := X_Dst;
Y0_Dst : Natural := Y_Dst;
X0_Bg : Natural := X_Bg;
Y0_Bg : Natural := Y_Bg;
W : Natural := Width;
H : Natural := Height;
begin
if Src_Buffer.Swapped then
X0_Src := Y_Src;
Y0_Src := Src_Buffer.Width - X_Src - Width;
end if;
if Dst_Buffer.Swapped then
X0_Dst := Y_Dst;
Y0_Dst := Dst_Buffer.Width - X_Dst - Width;
W := Height;
H := Width;
end if;
if Bg_Buffer.Addr = System.Null_Address then
DMA_Buf_Bg := STM32.DMA2D.Null_Buffer;
X0_Bg := 0;
Y0_Bg := 0;
elsif Bg_Buffer.Swapped then
X0_Bg := Y_Bg;
Y0_Bg := Bg_Buffer.Width - X_Bg - Width;
end if;
Cortex_M.Cache.Clean_DCache (Src_Buffer.Addr, Src_Buffer.Buffer_Size);
DMA2D_Copy_Rect
(DMA_Buf_Src, X0_Src, Y0_Src,
DMA_Buf_Dst, X0_Dst, Y0_Dst,
DMA_Buf_Bg, X0_Bg, Y0_Bg,
W, H,
Synchronous => Synchronous);
end Copy_Rect;
-------------------
-- Wait_Transfer --
-------------------
overriding procedure Wait_Transfer (Buffer : DMA2D_Bitmap_Buffer)
is
begin
DMA2D_Wait_Transfer;
Cortex_M.Cache.Clean_Invalidate_DCache
(Start => Buffer.Addr,
Len => Buffer.Buffer_Size);
end Wait_Transfer;
end STM32.DMA2D_Bitmap;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-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 Ada.Unchecked_Conversion;
with Cortex_M.Cache; use Cortex_M.Cache;
with STM32.DMA2D; use STM32.DMA2D;
package body STM32.DMA2D_Bitmap is
function To_DMA2D_CM is new Ada.Unchecked_Conversion
(HAL.Bitmap.Bitmap_Color_Mode, STM32.DMA2D.DMA2D_Color_Mode);
function To_DMA2D_Color is new Ada.Unchecked_Conversion
(HAL.Bitmap.Bitmap_Color, STM32.DMA2D.DMA2D_Color);
---------------------
-- To_DMA2D_Buffer --
---------------------
function To_DMA2D_Buffer
(Buffer : HAL.Bitmap.Bitmap_Buffer'Class) return DMA2D_Buffer
is
Color_Mode : constant DMA2D_Color_Mode :=
To_DMA2D_CM (Buffer.Color_Mode);
Ret : DMA2D_Buffer (Color_Mode);
begin
Ret.Addr := Buffer.Addr;
Ret.Width := (if Buffer.Swapped then Buffer.Height
else Buffer.Width);
Ret.Height := (if Buffer.Swapped then Buffer.Width
else Buffer.Height);
return Ret;
end To_DMA2D_Buffer;
---------------
-- Set_Pixel --
---------------
overriding procedure Set_Pixel
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural;
Value : UInt32)
is
begin
DMA2D_Wait_Transfer;
HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel (X, Y, Value);
end Set_Pixel;
---------------------
-- Set_Pixel_Blend --
---------------------
overriding procedure Set_Pixel_Blend
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural;
Value : HAL.Bitmap.Bitmap_Color)
is
DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer);
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
if not Buffer.Swapped then
DMA2D_Set_Pixel_Blend
(Buffer => DMA_Buf,
X => X,
Y => Y,
Color => To_DMA2D_Color (Value));
else
DMA2D_Set_Pixel_Blend
(Buffer => DMA_Buf,
X => Y,
Y => Buffer.Width - X - 1,
Color => To_DMA2D_Color (Value));
end if;
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Set_Pixel_Blend (X, Y, Value);
end if;
end Set_Pixel_Blend;
---------------
-- Get_Pixel --
---------------
overriding function Get_Pixel
(Buffer : DMA2D_Bitmap_Buffer;
X : Natural;
Y : Natural) return UInt32
is
begin
DMA2D_Wait_Transfer;
return HAL.Bitmap.Bitmap_Buffer (Buffer).Get_Pixel (X, Y);
end Get_Pixel;
----------
-- Fill --
----------
overriding procedure Fill
(Buffer : DMA2D_Bitmap_Buffer;
Color : UInt32)
is
begin
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
DMA2D_Fill (To_DMA2D_Buffer (Buffer), Color, True);
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Fill (Color);
end if;
end Fill;
---------------
-- Fill_Rect --
---------------
overriding procedure Fill_Rect
(Buffer : DMA2D_Bitmap_Buffer;
Color : UInt32;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer)
is
DMA_Buf : constant DMA2D_Buffer := To_DMA2D_Buffer (Buffer);
W, H : Integer;
begin
if X >= Buffer.Width or else Y >= Buffer.Height then
return;
end if;
if X + Width >= Buffer.Width then
W := Buffer.Width - X - 1;
else
W := Width;
end if;
if Y + Height >= Buffer.Height then
H := Buffer.Height - Y - 1;
else
H := Height;
end if;
if To_DMA2D_CM (Buffer.Color_Mode) in DMA2D_Dst_Color_Mode then
if not Buffer.Swapped then
DMA2D_Fill_Rect
(DMA_Buf,
Color => Color,
X => X,
Y => Y,
Width => W,
Height => H);
else
DMA2D_Fill_Rect
(DMA_Buf,
Color => Color,
X => Y,
Y => Buffer.Width - X - W,
Width => H,
Height => W);
end if;
else
HAL.Bitmap.Bitmap_Buffer (Buffer).Fill_Rect
(Color, X, Y, Width, Height);
end if;
end Fill_Rect;
---------------
-- Copy_Rect --
---------------
overriding procedure Copy_Rect
(Src_Buffer : HAL.Bitmap.Bitmap_Buffer'Class;
X_Src : Natural;
Y_Src : Natural;
Dst_Buffer : DMA2D_Bitmap_Buffer;
X_Dst : Natural;
Y_Dst : Natural;
Bg_Buffer : HAL.Bitmap.Bitmap_Buffer'Class;
X_Bg : Natural;
Y_Bg : Natural;
Width : Natural;
Height : Natural;
Synchronous : Boolean)
is
use type System.Address;
DMA_Buf_Src : constant DMA2D_Buffer := To_DMA2D_Buffer (Src_Buffer);
DMA_Buf_Dst : constant DMA2D_Buffer := To_DMA2D_Buffer (Dst_Buffer);
DMA_Buf_Bg : DMA2D_Buffer := To_DMA2D_Buffer (Bg_Buffer);
X0_Src : Natural := X_Src;
Y0_Src : Natural := Y_Src;
X0_Dst : Natural := X_Dst;
Y0_Dst : Natural := Y_Dst;
X0_Bg : Natural := X_Bg;
Y0_Bg : Natural := Y_Bg;
W : Natural := Width;
H : Natural := Height;
begin
if Src_Buffer.Swapped then
X0_Src := Y_Src;
Y0_Src := Src_Buffer.Width - X_Src - Width;
end if;
if Dst_Buffer.Swapped then
X0_Dst := Y_Dst;
Y0_Dst := Dst_Buffer.Width - X_Dst - Width;
W := Height;
H := Width;
end if;
if Bg_Buffer.Addr = System.Null_Address then
DMA_Buf_Bg := STM32.DMA2D.Null_Buffer;
X0_Bg := 0;
Y0_Bg := 0;
elsif Bg_Buffer.Swapped then
X0_Bg := Y_Bg;
Y0_Bg := Bg_Buffer.Width - X_Bg - Width;
end if;
Cortex_M.Cache.Clean_DCache (Src_Buffer.Addr, Src_Buffer.Buffer_Size);
DMA2D_Copy_Rect
(DMA_Buf_Src, X0_Src, Y0_Src,
DMA_Buf_Dst, X0_Dst, Y0_Dst,
DMA_Buf_Bg, X0_Bg, Y0_Bg,
W, H,
Synchronous => Synchronous);
end Copy_Rect;
-------------------
-- Wait_Transfer --
-------------------
overriding procedure Wait_Transfer (Buffer : DMA2D_Bitmap_Buffer)
is
begin
DMA2D_Wait_Transfer;
Cortex_M.Cache.Clean_Invalidate_DCache
(Start => Buffer.Addr,
Len => Buffer.Buffer_Size);
end Wait_Transfer;
end STM32.DMA2D_Bitmap;
|
Make sure Fill_Rect stays within the buffer layout.
|
Make sure Fill_Rect stays within the buffer layout.
Prevents memory corruption and display glitches when trying to draw out of
the buffer boundaries.
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library
|
992dd9dfefe2f8b06cdfe5076d4d8dedfc2baba0
|
src/security-policies-roles.ads
|
src/security-policies-roles.ads
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
-- In this policy, users are assigned one or several roles and permissions are
-- associated with roles. A permission is granted if the user has one of the roles required
-- by the permission.
--
-- === Policy creation ===
-- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Roles.Role_Policy_Access;
--
-- Create the role policy and register it in the policy manager as follows:
--
-- Policy := new Role_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles. When the role based policy is registered in the policy manager, the following
-- XML configuration is used:
--
-- <policy-rules>
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
-- ...
-- </policy-rules>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
--
-- Each role is identified by a name in the configuration file. It is represented by
-- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt>
-- is represented as an integer with a limit of 64 different roles.
--
-- === Assigning roles to users ===
-- A <tt>Security_Context</tt> must be associated with a set of roles before checking the
-- permission. This is done by using the <tt>Set_Role_Context</tt> operation:
--
-- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin");
--
package Security.Policies.Roles is
NAME : constant String := "Role-Policy";
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role principal context
-- ------------------------------
-- The <tt>Role_Principal_Context</tt> interface must be implemented by the user
-- <tt>Principal</tt> to be able to use the role based policy. The role based policy
-- controller will first check that the <tt>Principal</tt> implements that interface.
-- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user.
type Role_Principal_Context is limited interface;
function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract;
-- ------------------------------
-- Policy context
-- ------------------------------
-- The <b>Role_Policy_Context</b> gives security context information that the role
-- based policy can use to verify the permission.
type Role_Policy_Context is new Policy_Context with record
Roles : Role_Map;
end record;
type Role_Policy_Context_Access is access all Role_Policy_Context'Class;
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map);
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in Role_Policy) return String;
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Get the roles that grant the given permission.
function Get_Grants (Manager : in Role_Policy;
Permission : in Permissions.Permission_Index) return Role_Map;
-- Get the list of role names that are defined by the role map.
function Get_Role_Names (Manager : in Role_Policy;
Map : in Role_Map) return Role_Name_Array;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map);
-- Setup the XML parser to read the <b>role-permission</b> description.
overriding
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finalize the policy manager.
overriding
procedure Finalize (Policy : in out Role_Policy);
-- Get the role policy associated with the given policy manager.
-- Returns the role policy instance or null if it was not registered in the policy manager.
function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return Role_Policy_Access;
private
-- Array to map a permission index to a list of roles that are granted the permission.
type Permission_Role_Array is array (Permission_Index) of Role_Map;
type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Map_Name_Array := (others => null);
Next_Role : Role_Type := Role_Type'First;
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0);
Count : Natural := 0;
-- The Grants array indicates for each permission the list of roles
-- that are granted the permission. This array allows a O(1) lookup.
-- The implementation is limited to 256 permissions and 64 roles so this array uses 2K.
-- The default is that no role is assigned to the permission.
Grants : Permission_Role_Array := (others => (others => False));
end record;
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
-- In this policy, users are assigned one or several roles and permissions are
-- associated with roles. A permission is granted if the user has one of the roles required
-- by the permission.
--
-- === Policy creation ===
-- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Roles.Role_Policy_Access;
--
-- Create the role policy and register it in the policy manager as follows:
--
-- Policy := new Role_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles. When the role based policy is registered in the policy manager, the following
-- XML configuration is used:
--
-- <policy-rules>
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
-- ...
-- </policy-rules>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
--
-- Each role is identified by a name in the configuration file. It is represented by
-- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt>
-- is represented as an integer with a limit of 64 different roles.
--
-- === Assigning roles to users ===
-- A <tt>Security_Context</tt> must be associated with a set of roles before checking the
-- permission. This is done by using the <tt>Set_Role_Context</tt> operation:
--
-- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin");
--
package Security.Policies.Roles is
NAME : constant String := "Role-Policy";
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Get the number of roles set in the map.
function Get_Count (Map : in Role_Map) return Natural;
-- ------------------------------
-- Role principal context
-- ------------------------------
-- The <tt>Role_Principal_Context</tt> interface must be implemented by the user
-- <tt>Principal</tt> to be able to use the role based policy. The role based policy
-- controller will first check that the <tt>Principal</tt> implements that interface.
-- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user.
type Role_Principal_Context is limited interface;
function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract;
-- ------------------------------
-- Policy context
-- ------------------------------
-- The <b>Role_Policy_Context</b> gives security context information that the role
-- based policy can use to verify the permission.
type Role_Policy_Context is new Policy_Context with record
Roles : Role_Map;
end record;
type Role_Policy_Context_Access is access all Role_Policy_Context'Class;
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map);
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in Role_Policy) return String;
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Get the roles that grant the given permission.
function Get_Grants (Manager : in Role_Policy;
Permission : in Permissions.Permission_Index) return Role_Map;
-- Get the list of role names that are defined by the role map.
function Get_Role_Names (Manager : in Role_Policy;
Map : in Role_Map) return Role_Name_Array;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map);
-- Setup the XML parser to read the <b>role-permission</b> description.
overriding
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finalize the policy manager.
overriding
procedure Finalize (Policy : in out Role_Policy);
-- Get the role policy associated with the given policy manager.
-- Returns the role policy instance or null if it was not registered in the policy manager.
function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return Role_Policy_Access;
private
-- Array to map a permission index to a list of roles that are granted the permission.
type Permission_Role_Array is array (Permission_Index) of Role_Map;
type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Map_Name_Array := (others => null);
Next_Role : Role_Type := Role_Type'First;
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0);
Count : Natural := 0;
-- The Grants array indicates for each permission the list of roles
-- that are granted the permission. This array allows a O(1) lookup.
-- The implementation is limited to 256 permissions and 64 roles so this array uses 2K.
-- The default is that no role is assigned to the permission.
Grants : Permission_Role_Array := (others => (others => False));
end record;
end Security.Policies.Roles;
|
Declare the Get_Count function
|
Declare the Get_Count function
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
ab55b60417811d5a683af1baaff34c6a6ae8433e
|
src/security-policies-roles.ads
|
src/security-policies-roles.ads
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
--
-- A role is represented by a name in security configuration files.
package Security.Policies.Roles is
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
Invalid_Name : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : 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.
overriding
procedure Set_Reader_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
--
-- A role is represented by a name in security configuration files.
package Security.Policies.Roles is
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- 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.
overriding
procedure Set_Reader_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last));
Count : Natural := 0;
Manager : Role_Policy_Access;
end record;
end Security.Policies.Roles;
|
Fix Set_Reader_Config definition
|
Fix Set_Reader_Config definition
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
bf57a7c94840452b4f1fd40ea357c2dda55262ef
|
src/gen-artifacts-xmi.ads
|
src/gen-artifacts-xmi.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- 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 DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- 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 DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
Add the <<Nullable>> and <<Not Null>> stereotypes
|
Add the <<Nullable>> and <<Not Null>> stereotypes
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
efb8f718b9825c45388223c54ce1112b5f564a0d
|
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
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
43da69b236e6717e365ac512a186f866e7ca0352
|
src/asf-security-filters.ads
|
src/asf-security-filters.ads
|
-----------------------------------------------------------------------
-- 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 ASF.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Policies; use Security;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package ASF.Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Policies.Policy_Manager_Access := null;
end record;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Filters;
with ASF.Requests;
with ASF.Responses;
with ASF.Servlets;
with ASF.Sessions;
with ASF.Principals;
with Security.Policies; use Security;
-- The <b>Security.Filters</b> package defines a servlet filter that can be activated
-- on requests to authenticate users and verify they have the permission to view
-- a page.
package ASF.Security.Filters is
SID_COOKIE : constant String := "SID";
AID_COOKIE : constant String := "AID";
type Auth_Filter is new ASF.Filters.Filter with private;
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
overriding
procedure Initialize (Server : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
private
type Auth_Filter is new ASF.Filters.Filter with record
Manager : Policies.Policy_Manager_Access := null;
end record;
end ASF.Security.Filters;
|
Update the use the Filter_Config for the Initialize procedure
|
Update the use the Filter_Config for the Initialize procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a299ce75f6e9a438f2d7cb52b445f4154434558d
|
src/util-refs.ads
|
src/util-refs.ads
|
-----------------------------------------------------------------------
-- util-refs -- Reference Counting
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Concurrent.Counters;
-- The <b>Util.Refs</b> package provides support to implement object reference counting.
--
-- The data type to share through reference counting has to inherit from <b>Ref_Entity</b>
-- and the generic package <b>References</b> has to be instantiated.
-- <pre>
-- type Data is new Util.Refs.Ref_Entity with record ... end record;
-- type Data_Access is access all Data;
--
-- package Data_Ref is new Utils.Refs.References (Data, Data_Access);
-- </pre>
--
-- The reference is used as follows:
--
-- <pre>
-- D : Data_Ref.Ref := Data_Ref.Create; -- Allocate and get a reference
-- D2 : Data_Ref.Ref := D; -- Share reference
-- D.Value.all.XXXX := 0; -- Set data member XXXX
-- </pre>
--
-- When a reference is shared in a multi-threaded environment, the reference has to
-- be protected by using the <b>References.Atomic_Ref</b> type.
--
-- R : Data_Ref.Atomic_Ref;
--
-- The reference is then obtained by the protected operation <b>Get</b>.
--
-- D : Data_Ref.Ref := R.Get;
--
package Util.Refs is
-- Root of referenced objects.
type Ref_Entity is abstract tagged limited private;
-- Finalize the referenced object. This is called before the object is freed.
procedure Finalize (Object : in out Ref_Entity) is null;
generic
type Element_Type (<>) is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package Indefinite_References is
type Ref is new Ada.Finalization.Controlled with private;
-- Create an element and return a reference to that element.
function Create (Value : in Element_Access) return Ref;
-- Get the element access value.
function Value (Object : in Ref'Class) return Element_Access;
pragma Inline_Always (Value);
-- Returns true if the reference does not contain any element.
function Is_Null (Object : in Ref'Class) return Boolean;
pragma Inline_Always (Is_Null);
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
protected type Atomic_Ref is
-- Get the reference
function Get return Ref;
-- Change the reference
procedure Set (Object : in Ref);
private
Value : Ref;
end Atomic_Ref;
private
type Ref is new Ada.Finalization.Controlled with record
Target : Element_Access := null;
end record;
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
overriding
procedure Finalize (Obj : in out Ref);
-- Update the reference counter after an assignment.
overriding
procedure Adjust (Obj : in out Ref);
end Indefinite_References;
generic
type Element_Type is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package References is
package IR is new Indefinite_References (Element_Type, Element_Access);
subtype Ref is IR.Ref;
-- Create an element and return a reference to that element.
function Create return Ref;
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
subtype Atomic_Ref is IR.Atomic_Ref;
end References;
private
type Ref_Entity is abstract tagged limited record
Ref_Counter : Util.Concurrent.Counters.Counter;
end record;
end Util.Refs;
|
-----------------------------------------------------------------------
-- util-refs -- Reference Counting
-- Copyright (C) 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Concurrent.Counters;
-- The <b>Util.Refs</b> package provides support to implement object reference counting.
--
-- The data type to share through reference counting has to inherit from <b>Ref_Entity</b>
-- and the generic package <b>References</b> has to be instantiated.
-- <pre>
-- type Data is new Util.Refs.Ref_Entity with record ... end record;
-- type Data_Access is access all Data;
--
-- package Data_Ref is new Utils.Refs.References (Data, Data_Access);
-- </pre>
--
-- The reference is used as follows:
--
-- <pre>
-- D : Data_Ref.Ref := Data_Ref.Create; -- Allocate and get a reference
-- D2 : Data_Ref.Ref := D; -- Share reference
-- D.Value.all.XXXX := 0; -- Set data member XXXX
-- </pre>
--
-- When a reference is shared in a multi-threaded environment, the reference has to
-- be protected by using the <b>References.Atomic_Ref</b> type.
--
-- R : Data_Ref.Atomic_Ref;
--
-- The reference is then obtained by the protected operation <b>Get</b>.
--
-- D : Data_Ref.Ref := R.Get;
--
package Util.Refs is
pragma Preelaborate;
-- Root of referenced objects.
type Ref_Entity is abstract tagged limited private;
-- Finalize the referenced object. This is called before the object is freed.
procedure Finalize (Object : in out Ref_Entity) is null;
generic
type Element_Type (<>) is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package Indefinite_References is
type Ref is new Ada.Finalization.Controlled with private;
-- Create an element and return a reference to that element.
function Create (Value : in Element_Access) return Ref;
-- Get the element access value.
function Value (Object : in Ref'Class) return Element_Access;
pragma Inline_Always (Value);
-- Returns true if the reference does not contain any element.
function Is_Null (Object : in Ref'Class) return Boolean;
pragma Inline_Always (Is_Null);
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
protected type Atomic_Ref is
-- Get the reference
function Get return Ref;
-- Change the reference
procedure Set (Object : in Ref);
private
Value : Ref;
end Atomic_Ref;
private
type Ref is new Ada.Finalization.Controlled with record
Target : Element_Access := null;
end record;
-- Release the reference. Invoke <b>Finalize</b> and free the storage if it was
-- the last reference.
overriding
procedure Finalize (Obj : in out Ref);
-- Update the reference counter after an assignment.
overriding
procedure Adjust (Obj : in out Ref);
end Indefinite_References;
generic
type Element_Type is new Ref_Entity with private;
type Element_Access is access all Element_Type;
package References is
package IR is new Indefinite_References (Element_Type, Element_Access);
subtype Ref is IR.Ref;
-- Create an element and return a reference to that element.
function Create return Ref;
-- The <b>Atomic_Ref</b> protected type defines a reference to an
-- element which can be obtained and changed atomically. The default
-- Ada construct:
--
-- Ref1 := Ref2;
--
-- does not guarantee atomicity of the copy (assignment) and the increment
-- of the reference counter (Adjust operation). To replace shared reference
-- by another one, the whole assignment and Adjust have to be protected.
-- This is achieved by this protected type through the <b>Get</b> and <b>Set</b>
subtype Atomic_Ref is IR.Atomic_Ref;
end References;
private
type Ref_Entity is abstract tagged limited record
Ref_Counter : Util.Concurrent.Counters.Counter;
end record;
end Util.Refs;
|
Add pragma Preelaborate on Util.Refs package
|
Add pragma Preelaborate on Util.Refs package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
562c27c9520c5d898b08231d3689a09f1a3f2be9
|
src/security-contexts.adb
|
src/security-contexts.adb
|
-----------------------------------------------------------------------
-- security-contexts -- Context to provide security information and verify permissions
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Security.Controllers;
package body Security.Contexts is
package Task_Context is new Ada.Task_Attributes
(Security_Context_Access, null);
-- ------------------------------
-- Get the application associated with the current service operation.
-- ------------------------------
function Get_User_Principal (Context : in Security_Context'Class)
return Security.Principal_Access is
begin
return Context.Principal;
end Get_User_Principal;
-- ------------------------------
-- Get the permission manager.
-- ------------------------------
function Get_Permission_Manager (Context : in Security_Context'Class)
return Security.Permissions.Permission_Manager_Access is
begin
return Context.Manager;
end Get_Permission_Manager;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
procedure Has_Permission (Context : in out Security_Context;
Permission : in Security.Permissions.Permission_Index;
Result : out Boolean) is
use type Security.Permissions.Controller_Access;
use type Security.Permissions.Permission_Manager_Access;
begin
if Context.Manager = null then
Result := False;
return;
end if;
declare
C : constant Permissions.Controller_Access := Context.Manager.Get_Controller (Permission);
begin
if C = null then
Result := False;
else
-- Result := C.Has_Permission (Context);
Result := False;
end if;
end;
end Has_Permission;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
procedure Has_Permission (Context : in out Security_Context;
Permission : in String;
Result : out Boolean) is
Index : constant Permissions.Permission_Index
:= Permissions.Get_Permission_Index (Permission);
begin
Security_Context'Class (Context).Has_Permission (Index, Result);
end Has_Permission;
-- ------------------------------
-- Initializes the service context. By creating the <b>Security_Context</b> variable,
-- the instance will be associated with the current task attribute. If the current task
-- already has a security context, the new security context is installed, the old one
-- being kept.
-- ------------------------------
overriding
procedure Initialize (Context : in out Security_Context) is
begin
Context.Previous := Task_Context.Value;
Task_Context.Set_Value (Context'Unchecked_Access);
end Initialize;
-- ------------------------------
-- Finalize the security context releases any object. The previous security context is
-- restored to the current task attribute.
-- ------------------------------
overriding
procedure Finalize (Context : in out Security_Context) is
begin
Task_Context.Set_Value (Context.Previous);
end Finalize;
-- ------------------------------
-- Add a context information represented by <b>Value</b> under the name identified by
-- <b>Name</b> in the security context <b>Context</b>.
-- ------------------------------
procedure Add_Context (Context : in out Security_Context;
Name : in String;
Value : in String) is
begin
Context.Context.Include (Key => Name,
New_Item => Value);
end Add_Context;
-- ------------------------------
-- Get the context information registered under the name <b>Name</b> in the security
-- context <b>Context</b>.
-- Raises <b>Invalid_Context</b> if there is no such information.
-- ------------------------------
function Get_Context (Context : in Security_Context;
Name : in String) return String is
Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name);
begin
if Util.Strings.Maps.Has_Element (Pos) then
return Util.Strings.Maps.Element (Pos);
else
raise Invalid_Context;
end if;
end Get_Context;
-- ------------------------------
-- Returns True if a context information was registered under the name <b>Name</b>.
-- ------------------------------
function Has_Context (Context : in Security_Context;
Name : in String) return Boolean is
use type Util.Strings.Maps.Cursor;
begin
return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element;
end Has_Context;
-- ------------------------------
-- Set the current application and user context.
-- ------------------------------
procedure Set_Context (Context : in out Security_Context;
Manager : in Security.Permissions.Permission_Manager_Access;
Principal : in Security.Principal_Access) is
begin
Context.Manager := Manager;
Context.Principal := Principal;
end Set_Context;
-- ------------------------------
-- Get the current security context.
-- Returns null if the current thread is not associated with any security context.
-- ------------------------------
function Current return Security_Context_Access is
begin
return Task_Context.Value;
end Current;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is
Result : Boolean;
Context : constant Security_Context_Access := Current;
begin
if Context = null then
return False;
else
Context.Has_Permission (Permission, Result);
return Result;
end if;
end Has_Permission;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
function Has_Permission (Permission : in String) return Boolean is
Result : Boolean;
Context : constant Security_Context_Access := Current;
begin
if Context = null then
return False;
else
Context.Has_Permission (Permission, Result);
return Result;
end if;
end Has_Permission;
end Security.Contexts;
|
-----------------------------------------------------------------------
-- security-contexts -- Context to provide security information and verify permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Security.Controllers;
package body Security.Contexts is
package Task_Context is new Ada.Task_Attributes
(Security_Context_Access, null);
-- ------------------------------
-- Get the application associated with the current service operation.
-- ------------------------------
function Get_User_Principal (Context : in Security_Context'Class)
return Security.Principal_Access is
begin
return Context.Principal;
end Get_User_Principal;
-- ------------------------------
-- Get the permission manager.
-- ------------------------------
function Get_Permission_Manager (Context : in Security_Context'Class)
return Security.Policies.Policy_Manager_Access is
begin
return Context.Manager;
end Get_Permission_Manager;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
procedure Has_Permission (Context : in out Security_Context;
Permission : in Security.Permissions.Permission_Index;
Result : out Boolean) is
use type Security.Policies.Controller_Access;
use type Security.Policies.Policy_Manager_Access;
begin
if Context.Manager = null then
Result := False;
return;
end if;
declare
C : constant Policies.Controller_Access := Context.Manager.Get_Controller (Permission);
begin
if C = null then
Result := False;
else
-- Result := C.Has_Permission (Context);
Result := False;
end if;
end;
end Has_Permission;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
procedure Has_Permission (Context : in out Security_Context;
Permission : in String;
Result : out Boolean) is
Index : constant Permissions.Permission_Index
:= Permissions.Get_Permission_Index (Permission);
begin
Security_Context'Class (Context).Has_Permission (Index, Result);
end Has_Permission;
-- ------------------------------
-- Initializes the service context. By creating the <b>Security_Context</b> variable,
-- the instance will be associated with the current task attribute. If the current task
-- already has a security context, the new security context is installed, the old one
-- being kept.
-- ------------------------------
overriding
procedure Initialize (Context : in out Security_Context) is
begin
Context.Previous := Task_Context.Value;
Task_Context.Set_Value (Context'Unchecked_Access);
end Initialize;
-- ------------------------------
-- Finalize the security context releases any object. The previous security context is
-- restored to the current task attribute.
-- ------------------------------
overriding
procedure Finalize (Context : in out Security_Context) is
begin
Task_Context.Set_Value (Context.Previous);
end Finalize;
-- ------------------------------
-- Add a context information represented by <b>Value</b> under the name identified by
-- <b>Name</b> in the security context <b>Context</b>.
-- ------------------------------
procedure Add_Context (Context : in out Security_Context;
Name : in String;
Value : in String) is
begin
Context.Context.Include (Key => Name,
New_Item => Value);
end Add_Context;
-- ------------------------------
-- Get the context information registered under the name <b>Name</b> in the security
-- context <b>Context</b>.
-- Raises <b>Invalid_Context</b> if there is no such information.
-- ------------------------------
function Get_Context (Context : in Security_Context;
Name : in String) return String is
Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name);
begin
if Util.Strings.Maps.Has_Element (Pos) then
return Util.Strings.Maps.Element (Pos);
else
raise Invalid_Context;
end if;
end Get_Context;
-- ------------------------------
-- Returns True if a context information was registered under the name <b>Name</b>.
-- ------------------------------
function Has_Context (Context : in Security_Context;
Name : in String) return Boolean is
use type Util.Strings.Maps.Cursor;
begin
return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element;
end Has_Context;
-- ------------------------------
-- Set the current application and user context.
-- ------------------------------
procedure Set_Context (Context : in out Security_Context;
Manager : in Security.Policies.Policy_Manager_Access;
Principal : in Security.Principal_Access) is
begin
Context.Manager := Manager;
Context.Principal := Principal;
end Set_Context;
-- ------------------------------
-- Get the current security context.
-- Returns null if the current thread is not associated with any security context.
-- ------------------------------
function Current return Security_Context_Access is
begin
return Task_Context.Value;
end Current;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is
Result : Boolean;
Context : constant Security_Context_Access := Current;
begin
if Context = null then
return False;
else
Context.Has_Permission (Permission, Result);
return Result;
end if;
end Has_Permission;
-- ------------------------------
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
-- ------------------------------
function Has_Permission (Permission : in String) return Boolean is
Result : Boolean;
Context : constant Security_Context_Access := Current;
begin
if Context = null then
return False;
else
Context.Has_Permission (Permission, Result);
return Result;
end if;
end Has_Permission;
end Security.Contexts;
|
Use the policy manager
|
Use the policy manager
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
c1a052f6bbc0ea10c11609df8f4844bbb1191a48
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Probes;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access
:= new MAT.Memory.Probes.Memory_Probe_Type;
begin
-- Memory.Manager := Memory_Probe.all'Access;
Memory_Probe.Data := Memory'Unrestricted_Access;
MAT.Memory.Probes.Register (Manager, Memory_Probe);
end Initialize;
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info) is
begin
Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-"
& MAT.Types.Hex_Image (Region.End_Addr) & "]");
Memory.Memory.Add_Region (Region);
end Add_Region;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map) is
begin
Memory.Memory.Thread_Information (Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
Memory.Memory.Frame_Information (Level, Frames);
end Frame_Information;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat) is
begin
Memory.Memory.Stat_Information (Result);
end Stat_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Filter, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Region : in Region_Info) is
begin
Regions.Insert (Region.Start_Addr, Region);
end Add_Region;
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation);
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
pragma Unreferenced (Key);
begin
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
Pos : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end if;
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Threads : in out Memory_Info_Map) is
begin
MAT.Memory.Tools.Thread_Information (Used_Slots, Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into);
end Find;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Probes;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access
:= new MAT.Memory.Probes.Memory_Probe_Type;
begin
-- Memory.Manager := Memory_Probe.all'Access;
Memory_Probe.Data := Memory'Unrestricted_Access;
MAT.Memory.Probes.Register (Manager, Memory_Probe);
end Initialize;
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Memory : in out Target_Memory;
Region : in Region_Info) is
begin
Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-"
& MAT.Types.Hex_Image (Region.End_Addr) & "]");
Memory.Memory.Add_Region (Region);
end Add_Region;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Malloc (Addr, Slot);
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Free (Addr, Slot);
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Memory : in out Target_Memory;
Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot);
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Memory : in out Target_Memory;
Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
Memory.Memory.Create_Frame (Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
Memory.Memory.Size_Information (Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map) is
begin
Memory.Memory.Thread_Information (Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
Memory.Memory.Frame_Information (Level, Frames);
end Frame_Information;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat) is
begin
Memory.Memory.Stat_Information (Result);
end Stat_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
Memory.Memory.Find (From, To, Filter, Into);
end Find;
protected body Memory_Allocator is
-- ------------------------------
-- Add the memory region from the list of memory region managed by the program.
-- ------------------------------
procedure Add_Region (Region : in Region_Info) is
begin
Regions.Insert (Region.Start_Addr, Region);
end Add_Region;
-- ------------------------------
-- Remove the memory region [Addr .. Addr + Size] from the free list.
-- ------------------------------
procedure Remove_Free (Addr : in MAT.Types.Target_Addr;
Size : in MAT.Types.Target_Size) is
Iter : Allocation_Cursor;
Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size);
Slot : Allocation;
begin
-- Walk the list of free blocks and remove all the blocks which intersect the region
-- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near
-- the address. Slots are then removed when they intersect the malloc'ed region.
Iter := Freed_Slots.Floor (Addr);
while Allocation_Maps.Has_Element (Iter) loop
declare
Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter);
begin
exit when Freed_Addr > Last;
Slot := Allocation_Maps.Element (Iter);
if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then
if Stats.Total_Free > Slot.Size then
Stats.Total_Free := Stats.Total_Free - Slot.Size;
else
Stats.Total_Free := 0;
end if;
Freed_Slots.Delete (Iter);
Iter := Freed_Slots.Floor (Addr);
else
Allocation_Maps.Next (Iter);
end if;
end;
end loop;
end Remove_Free;
-- ------------------------------
-- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted
-- in the used slots map. The freed slots that intersect the malloc'ed region are
-- removed from the freed map.
-- ------------------------------
procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr),
MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Malloc_Count := Stats.Malloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Remove_Free (Addr, Slot.Size);
Used_Slots.Insert (Addr, Slot);
end if;
end Probe_Malloc;
-- ------------------------------
-- Take into account a free probe. Add the memory slot in the freed map and remove
-- the slot from the used slots map.
-- ------------------------------
procedure Probe_Free (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Item : Allocation;
Iter : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr));
end if;
Stats.Free_Count := Stats.Free_Count + 1;
Iter := Used_Slots.Find (Addr);
if Allocation_Maps.Has_Element (Iter) then
Item := Allocation_Maps.Element (Iter);
if Stats.Total_Alloc >= Item.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Item.Size;
else
Stats.Total_Alloc := 0;
end if;
Stats.Total_Free := Stats.Total_Free + Item.Size;
MAT.Frames.Release (Item.Frame);
Used_Slots.Delete (Iter);
Item.Frame := Slot.Frame;
Freed_Slots.Insert (Addr, Item);
end if;
end Probe_Free;
-- ------------------------------
-- Take into account a realloc probe. The old memory slot represented by Old_Addr is
-- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is
-- inserted in the used slots map.
-- ------------------------------
procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr;
Old_Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation);
procedure Update_Size (Key : in MAT.Types.Target_Addr;
Element : in out Allocation) is
pragma Unreferenced (Key);
begin
if Stats.Total_Alloc >= Element.Size then
Stats.Total_Alloc := Stats.Total_Alloc - Element.Size;
else
Stats.Total_Alloc := 0;
end if;
Element.Size := Slot.Size;
MAT.Frames.Release (Element.Frame);
Element.Frame := Slot.Frame;
end Update_Size;
Pos : Allocation_Cursor;
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr),
MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size));
end if;
Stats.Realloc_Count := Stats.Realloc_Count + 1;
if Addr /= 0 then
Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size;
Pos := Used_Slots.Find (Old_Addr);
if Allocation_Maps.Has_Element (Pos) then
if Addr = Old_Addr then
Used_Slots.Update_Element (Pos, Update_Size'Access);
else
Used_Slots.Delete (Pos);
Used_Slots.Insert (Addr, Slot);
end if;
else
Used_Slots.Insert (Addr, Slot);
end if;
Remove_Free (Addr, Slot.Size);
end if;
end Probe_Realloc;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Create_Frame (Pc : in MAT.Frames.Frame_Table;
Result : out MAT.Frames.Frame_Type) is
begin
MAT.Frames.Insert (Frames, Pc, Result);
end Create_Frame;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is
begin
MAT.Memory.Tools.Size_Information (Used_Slots, Sizes);
end Size_Information;
-- ------------------------------
-- Collect the information about threads and the memory allocations they've made.
-- ------------------------------
procedure Thread_Information (Threads : in out Memory_Info_Map) is
begin
MAT.Memory.Tools.Thread_Information (Used_Slots, Threads);
end Thread_Information;
-- ------------------------------
-- Collect the information about frames and the memory allocations they've made.
-- ------------------------------
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map) is
begin
MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames);
end Frame_Information;
-- ------------------------------
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
-- ------------------------------
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map) is
begin
MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into);
end Find;
-- ------------------------------
-- Get the global memory and allocation statistics.
-- ------------------------------
procedure Stat_Information (Result : out Memory_Stat) is
begin
Result := Stats;
end Stat_Information;
end Memory_Allocator;
end MAT.Memory.Targets;
|
Check if the address returned by malloc is 0 in which case don't insert it in the map: this is a memory allocation failure
|
Check if the address returned by malloc is 0 in which case don't
insert it in the map: this is a memory allocation failure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
34cbbc0c9ffe5cf4080990b1ee037e5867052c7e
|
matp/src/events/mat-events-probes.adb
|
matp/src/events/mat-events-probes.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Probe : in Probe_Type;
Id : in MAT.Events.Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in MAT.Events.Event_Id_Type) is
begin
Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
Probe.Owner := Into'Unchecked_Access;
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref
(MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop -- reverse Count .. 1 loop
if Count < Frame.Depth then
Frame.Frame (Count - I + 1) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
-- Convert the time in usec to make computation easier.
Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000;
Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
exception
when E : others =>
Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count));
raise;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Probe : in Probe_Type;
Id : in MAT.Events.Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in MAT.Events.Event_Id_Type) is
begin
Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := MAT.Frames.Create_Root;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
Probe.Owner := Into'Unchecked_Access;
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref
(MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop -- reverse Count .. 1 loop
if Count < Frame.Depth then
Frame.Frame (Count - I + 1) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
-- Convert the time in usec to make computation easier.
Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000;
Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
exception
when E : others =>
Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count));
raise;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Prev_Id := 0;
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
MAT.Frames.Insert (Frame => Client.Frames,
Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
end MAT.Events.Probes;
|
Clear the Event.Prev_Id before creating a new event
|
Clear the Event.Prev_Id before creating a new event
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f9be9b768ed61f6639a6da737f73281ec6c6c353
|
src/wiki-plugins.ads
|
src/wiki-plugins.ads
|
-----------------------------------------------------------------------
-- wiki-plugins -- Wiki plugins
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
-- == Plugins ==
-- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki
-- engine to provide pluggable extensions in the Wiki.
--
package Wiki.Plugins is
pragma Preelaborate;
type Wiki_Plugin is limited interface;
type Wiki_Plugin_Access is access all Wiki_Plugin'Class;
-- Expand the plugin configured with the parameters for the document.
procedure Expand (Plugin : in out Wiki_Plugin;
Document : in out Wiki.Documents.Document_Reader'Class;
Params : in out Wiki.Attributes.Attribute_List_Type) is abstract;
end Wiki.Plugins;
|
-----------------------------------------------------------------------
-- wiki-plugins -- Wiki plugins
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Nodes;
-- == Plugins ==
-- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki
-- engine to provide pluggable extensions in the Wiki.
--
package Wiki.Plugins is
pragma Preelaborate;
type Wiki_Plugin is limited interface;
type Wiki_Plugin_Access is access all Wiki_Plugin'Class;
-- Expand the plugin configured with the parameters for the document.
procedure Expand (Plugin : in out Wiki_Plugin;
Document : in out Wiki.Nodes.Document;
Params : in out Wiki.Attributes.Attribute_List_Type) is abstract;
end Wiki.Plugins;
|
Use the Document type
|
Use the Document type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
6ff4ad41424a8edebaa331f8ac79049d5e8afe29
|
src/ado-audits.adb
|
src/ado-audits.adb
|
-----------------------------------------------------------------------
-- ado-audits -- Auditing support
-- 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 Ada.Unchecked_Deallocation;
with Util.Beans.Objects.Time;
with ADO.Utils;
package body ADO.Audits is
use Ada.Strings.Unbounded;
use type ADO.Schemas.Column_Index;
use type Ada.Calendar.Time;
package UBOT renames Util.Beans.Objects.Time;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Audit_Array,
Name => Audit_Array_Access);
procedure Save (Object : in out Auditable_Object_Record'Class;
Session : in out ADO.Sessions.Master_Session'Class) is
Manager : constant access Audit_Manager'Class := Session.Get_Audit_Manager;
Audits : constant Audit_Array_Access := Object.Audits;
Last : Audit_Info_Index;
begin
if Manager /= null and Audits /= null then
Last := 1;
for Pos in Audits'Range loop
exit when Audits (Pos).Field = 0;
Last := Pos;
end loop;
Manager.Save (Session, Object, Audits (1 .. Last));
end if;
Free (Object.Audits);
end Save;
-- --------------------
-- Record an audit information for a field.
-- --------------------
procedure Audit_Field (Object : in out Auditable_Object_Record;
Field : in ADO.Schemas.Column_Index;
Old_Value : in UBO.Object;
New_Value : in UBO.Object) is
Audits : Audit_Array_Access := Object.Audits;
begin
if Audits = null then
Audits := new Audit_Array (1 .. Audit_Info_Index (Object.With_Audit.Count));
Object.Audits := Audits;
end if;
for Pos in Object.Audits'Range loop
if Audits (Pos).Field = Field then
Audits (Pos).New_Value := New_Value;
return;
end if;
if Audits (Pos).Field = 0 then
Audits (Pos).Field := Field;
Audits (Pos).Old_Value := Old_Value;
Audits (Pos).New_Value := New_Value;
return;
end if;
end loop;
end Audit_Field;
-- --------------------
-- Release the object.
-- --------------------
overriding
procedure Finalize (Object : in out Auditable_Object_Record) is
begin
Free (Object.Audits);
ADO.Objects.Finalize (ADO.Objects.Object_Record (Object));
end Finalize;
procedure Set_Field_Unbounded_String (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Ada.Strings.Unbounded.Unbounded_String;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Unbounded_String;
procedure Set_Field_String (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Ada.Strings.Unbounded.Unbounded_String;
Value : in String) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Ada.Strings.Unbounded.Set_Unbounded_String (Into, Value);
Object.Set_Field (Field);
end if;
end Set_Field_String;
procedure Set_Field_String (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_String;
Value : in String) is
begin
if Into.Is_Null or else Into.Value /= Value then
if Into.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBO.To_Object (Value));
else
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.To_Object (Value));
end if;
Into.Is_Null := False;
Ada.Strings.Unbounded.Set_Unbounded_String (Into.Value, Value);
Object.Set_Field (Field);
end if;
end Set_Field_String;
procedure Set_Field_String (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_String;
Value : in ADO.Nullable_String) is
begin
if Into.Is_Null then
if not Value.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBO.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
elsif Value.Is_Null then
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.Null_Object);
Into := Value;
Object.Set_Field (Field);
elsif Into.Value /= Value.Value then
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_String;
procedure Set_Field_Time (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Ada.Calendar.Time;
Value : in Ada.Calendar.Time) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBOT.To_Object (Into), UBOT.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Time;
procedure Set_Field_Time (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_Time;
Value : in ADO.Nullable_Time) is
begin
if Into.Is_Null then
if not Value.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBOT.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
elsif Value.Is_Null then
Object.Audit_Field (Field, UBOT.To_Object (Into.Value), UBO.Null_Object);
Into := Value;
Object.Set_Field (Field);
elsif Into.Value /= Value.Value then
Object.Audit_Field (Field, UBOT.To_Object (Into.Value), UBOT.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Time;
procedure Set_Field_Integer (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Integer;
Value : in Integer) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Integer;
procedure Set_Field_Integer (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_Integer;
Value : in ADO.Nullable_Integer) is
begin
if Into.Is_Null then
if not Value.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBO.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
elsif Value.Is_Null then
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.Null_Object);
Into := Value;
Object.Set_Field (Field);
elsif Into.Value /= Value.Value then
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Integer;
procedure Set_Field_Natural (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Natural;
Value : in Natural) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Natural;
procedure Set_Field_Positive (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Positive;
Value : in Positive) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Positive;
procedure Set_Field_Boolean (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Boolean;
Value : in Boolean) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Boolean;
procedure Set_Field_Object (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Objects.Object_Ref'Class;
Value : in ADO.Objects.Object_Ref'Class) is
use type ADO.Objects.Object_Ref;
begin
if Into /= Value then
Object.Audit_Field (Field, ADO.Objects.To_Object (Into.Get_Key),
ADO.Objects.To_Object (Value.Get_Key));
ADO.Objects.Set_Field_Object (Object, Field, Into, Value);
end if;
end Set_Field_Object;
procedure Set_Field_Identifier (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Identifier;
Value : in ADO.Identifier) is
begin
if Into /= Value then
Object.Audit_Field (Field, Utils.To_Object (Into), Utils.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Identifier;
procedure Set_Field_Entity_Type (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Entity_Type;
Value : in ADO.Entity_Type) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Natural (Into)),
UBO.To_Object (Natural (Value)));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Entity_Type;
procedure Set_Field_Entity_Type (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_Entity_Type;
Value : in ADO.Nullable_Entity_Type) is
begin
if Into.Is_Null then
if not Value.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBO.To_Object (Natural (Value.Value)));
Into := Value;
Object.Set_Field (Field);
end if;
elsif Value.Is_Null then
Object.Audit_Field (Field, UBO.To_Object (Natural (Into.Value)), UBO.Null_Object);
Into := Value;
Object.Set_Field (Field);
elsif Into.Value /= Value.Value then
Object.Audit_Field (Field, UBO.To_Object (Natural (Into.Value)),
UBO.To_Object (Natural (Value.Value)));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Entity_Type;
procedure Set_Field_Key_Value (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Value : in ADO.Identifier) is
begin
if Object.Get_Key_Value /= Value then
Object.Audit_Field (Field, ADO.Objects.To_Object (Object.Get_Key),
Utils.To_Object (Value));
ADO.Objects.Set_Key_Value (Object, Value);
Object.Set_Field (Field);
end if;
end Set_Field_Key_Value;
procedure Set_Field_Key_Value (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Value : in String) is
begin
if Object.Get_Key_Value /= Value then
Object.Audit_Field (Field, ADO.Objects.To_Object (Object.Get_Key),
UBO.To_Object (Value));
ADO.Objects.Set_Key_Value (Object, Value);
Object.Set_Field (Field);
end if;
end Set_Field_Key_Value;
procedure Set_Field_Key_Value (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
if Object.Get_Key_Value /= Value then
Object.Audit_Field (Field, ADO.Objects.To_Object (Object.Get_Key),
UBO.To_Object (Value));
ADO.Objects.Set_Key_Value (Object, Value);
Object.Set_Field (Field);
end if;
end Set_Field_Key_Value;
procedure Set_Field_Operation (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out T;
Value : in T) is
begin
if Into /= Value then
Object.Audit_Field (Field, To_Object (Into), To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Operation;
end ADO.Audits;
|
-----------------------------------------------------------------------
-- ado-audits -- Auditing support
-- 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 Ada.Unchecked_Deallocation;
with Util.Beans.Objects.Time;
with ADO.Utils;
package body ADO.Audits is
use Ada.Strings.Unbounded;
use type ADO.Schemas.Column_Index;
use type Ada.Calendar.Time;
package UBOT renames Util.Beans.Objects.Time;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Audit_Array,
Name => Audit_Array_Access);
procedure Save (Object : in out Auditable_Object_Record'Class;
Session : in out ADO.Sessions.Master_Session'Class) is
Manager : constant access Audit_Manager'Class := Session.Get_Audit_Manager;
Audits : constant Audit_Array_Access := Object.Audits;
Last : Audit_Info_Index;
begin
if Manager /= null and Audits /= null then
Last := 1;
for Pos in Audits'Range loop
exit when Audits (Pos).Field = 0;
Last := Pos;
end loop;
Manager.Save (Session, Object, Audits (1 .. Last));
end if;
Free (Object.Audits);
end Save;
-- --------------------
-- Record an audit information for a field.
-- --------------------
procedure Audit_Field (Object : in out Auditable_Object_Record;
Field : in ADO.Schemas.Column_Index;
Old_Value : in UBO.Object;
New_Value : in UBO.Object) is
Audits : Audit_Array_Access := Object.Audits;
begin
if Audits = null then
Audits := new Audit_Array (1 .. Audit_Info_Index (Object.With_Audit.Count));
Object.Audits := Audits;
end if;
for Pos in Object.Audits'Range loop
if Audits (Pos).Field = Field then
Audits (Pos).New_Value := New_Value;
return;
end if;
if Audits (Pos).Field = 0 then
Audits (Pos).Field := Field;
Audits (Pos).Old_Value := Old_Value;
Audits (Pos).New_Value := New_Value;
return;
end if;
end loop;
end Audit_Field;
-- --------------------
-- Release the object.
-- --------------------
overriding
procedure Finalize (Object : in out Auditable_Object_Record) is
begin
Free (Object.Audits);
ADO.Objects.Finalize (ADO.Objects.Object_Record (Object));
end Finalize;
procedure Set_Field_Unbounded_String (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Ada.Strings.Unbounded.Unbounded_String;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Unbounded_String;
procedure Set_Field_String (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Ada.Strings.Unbounded.Unbounded_String;
Value : in String) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Ada.Strings.Unbounded.Set_Unbounded_String (Into, Value);
Object.Set_Field (Field);
end if;
end Set_Field_String;
procedure Set_Field_String (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_String;
Value : in String) is
begin
if Into.Is_Null or else Into.Value /= Value then
if Into.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBO.To_Object (Value));
else
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.To_Object (Value));
end if;
Into.Is_Null := False;
Ada.Strings.Unbounded.Set_Unbounded_String (Into.Value, Value);
Object.Set_Field (Field);
end if;
end Set_Field_String;
procedure Set_Field_String (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_String;
Value : in ADO.Nullable_String) is
begin
if Into.Is_Null then
if not Value.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBO.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
elsif Value.Is_Null then
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.Null_Object);
Into := Value;
Object.Set_Field (Field);
elsif Into.Value /= Value.Value then
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_String;
procedure Set_Field_Time (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Ada.Calendar.Time;
Value : in Ada.Calendar.Time) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBOT.To_Object (Into), UBOT.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Time;
procedure Set_Field_Time (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_Time;
Value : in ADO.Nullable_Time) is
begin
if Into.Is_Null then
if not Value.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBOT.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
elsif Value.Is_Null then
Object.Audit_Field (Field, UBOT.To_Object (Into.Value), UBO.Null_Object);
Into := Value;
Object.Set_Field (Field);
elsif Into.Value /= Value.Value then
Object.Audit_Field (Field, UBOT.To_Object (Into.Value), UBOT.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Time;
procedure Set_Field_Integer (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Integer;
Value : in Integer) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Integer;
procedure Set_Field_Integer (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_Integer;
Value : in ADO.Nullable_Integer) is
begin
if Into.Is_Null then
if not Value.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBO.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
elsif Value.Is_Null then
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.Null_Object);
Into := Value;
Object.Set_Field (Field);
elsif Into.Value /= Value.Value then
Object.Audit_Field (Field, UBO.To_Object (Into.Value), UBO.To_Object (Value.Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Integer;
procedure Set_Field_Natural (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Natural;
Value : in Natural) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Natural;
procedure Set_Field_Positive (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Positive;
Value : in Positive) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Positive;
procedure Set_Field_Boolean (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Boolean;
Value : in Boolean) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Boolean;
procedure Set_Field_Float (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Float;
Value : in Float) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Float;
procedure Set_Field_Long_Float (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out Long_Float;
Value : in Long_Float) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Into), UBO.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Long_Float;
procedure Set_Field_Object (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Objects.Object_Ref'Class;
Value : in ADO.Objects.Object_Ref'Class) is
use type ADO.Objects.Object_Ref;
begin
if Into /= Value then
Object.Audit_Field (Field, ADO.Objects.To_Object (Into.Get_Key),
ADO.Objects.To_Object (Value.Get_Key));
ADO.Objects.Set_Field_Object (Object, Field, Into, Value);
end if;
end Set_Field_Object;
procedure Set_Field_Identifier (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Identifier;
Value : in ADO.Identifier) is
begin
if Into /= Value then
Object.Audit_Field (Field, Utils.To_Object (Into), Utils.To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Identifier;
procedure Set_Field_Entity_Type (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Entity_Type;
Value : in ADO.Entity_Type) is
begin
if Into /= Value then
Object.Audit_Field (Field, UBO.To_Object (Natural (Into)),
UBO.To_Object (Natural (Value)));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Entity_Type;
procedure Set_Field_Entity_Type (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out ADO.Nullable_Entity_Type;
Value : in ADO.Nullable_Entity_Type) is
begin
if Into.Is_Null then
if not Value.Is_Null then
Object.Audit_Field (Field, UBO.Null_Object, UBO.To_Object (Natural (Value.Value)));
Into := Value;
Object.Set_Field (Field);
end if;
elsif Value.Is_Null then
Object.Audit_Field (Field, UBO.To_Object (Natural (Into.Value)), UBO.Null_Object);
Into := Value;
Object.Set_Field (Field);
elsif Into.Value /= Value.Value then
Object.Audit_Field (Field, UBO.To_Object (Natural (Into.Value)),
UBO.To_Object (Natural (Value.Value)));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Entity_Type;
procedure Set_Field_Key_Value (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Value : in ADO.Identifier) is
begin
if Object.Get_Key_Value /= Value then
Object.Audit_Field (Field, ADO.Objects.To_Object (Object.Get_Key),
Utils.To_Object (Value));
ADO.Objects.Set_Key_Value (Object, Value);
Object.Set_Field (Field);
end if;
end Set_Field_Key_Value;
procedure Set_Field_Key_Value (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Value : in String) is
begin
if Object.Get_Key_Value /= Value then
Object.Audit_Field (Field, ADO.Objects.To_Object (Object.Get_Key),
UBO.To_Object (Value));
ADO.Objects.Set_Key_Value (Object, Value);
Object.Set_Field (Field);
end if;
end Set_Field_Key_Value;
procedure Set_Field_Key_Value (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
if Object.Get_Key_Value /= Value then
Object.Audit_Field (Field, ADO.Objects.To_Object (Object.Get_Key),
UBO.To_Object (Value));
ADO.Objects.Set_Key_Value (Object, Value);
Object.Set_Field (Field);
end if;
end Set_Field_Key_Value;
procedure Set_Field_Operation (Object : in out Auditable_Object_Record'Class;
Field : in Column_Index;
Into : in out T;
Value : in T) is
begin
if Into /= Value then
Object.Audit_Field (Field, To_Object (Into), To_Object (Value));
Into := Value;
Object.Set_Field (Field);
end if;
end Set_Field_Operation;
end ADO.Audits;
|
Implement Set_Field_Float and Set_Field_Long_Float
|
Implement Set_Field_Float and Set_Field_Long_Float
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
29e255e1f3bb8427d0b4a04c1f127b33ed9e6d43
|
src/wiki-nodes.adb
|
src/wiki-nodes.adb
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Wiki.Nodes is
-- ------------------------------
-- Append a node to the tag node.
-- ------------------------------
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access) is
begin
if Into.Children = null then
Into.Children := new Node_List;
Into.Children.Current := Into.Children.First'Access;
end if;
Append (Into.Children.all, Node);
end Append;
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access) is
Block : Node_List_Block_Access := Into.Current;
begin
if Block.Last = Block.Max then
Block.Next := new Node_List_Block (Block.Max * 2);
Block := Block.Next;
Into.Current := Block;
end if;
Block.Last := Block.Last + 1;
Block.List (Block.Last) := Node;
Into.Length := Into.Length + 1;
end Append;
-- ------------------------------
-- Finalize the node list to release the allocated memory.
-- ------------------------------
procedure Finalize (List : in out Node_List) is
procedure Free is
new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_List, Node_List_Access);
procedure Release (List : in Node_List_Block_Access);
procedure Free_Block (Block : in out Node_List_Block);
procedure Free_Block (Block : in out Node_List_Block) is
begin
for I in 1 .. Block.Last loop
if Block.List (I).Kind = N_TAG_START and then Block.List (I).Children /= null then
Finalize (Block.List (I).Children.all);
Free (Block.List (I).Children);
end if;
Free (Block.List (I));
end loop;
end Free_Block;
procedure Release (List : in Node_List_Block_Access) is
Next : Node_List_Block_Access := List;
Block : Node_List_Block_Access;
begin
while Next /= null loop
Block := Next;
Free_Block (Block.all);
Next := Next.Next;
Free (Block);
end loop;
end Release;
begin
Release (List.First.Next);
Free_Block (List.First);
end Finalize;
end Wiki.Nodes;
|
-----------------------------------------------------------------------
-- wiki-nodes -- Wiki Document Internal representation
-- Copyright (C) 2016, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Wiki.Nodes is
-- ------------------------------
-- Append a node to the tag node.
-- ------------------------------
procedure Append (Into : in Node_Type_Access;
Node : in Node_Type_Access) is
begin
if Into.Kind in N_HEADER .. N_DEFINITION then
if Into.Content = null then
Into.Content := new Node_List;
Into.Content.Current := Into.Content.First'Access;
end if;
Append (Into.Content.all, Node);
else
if Into.Children = null then
Into.Children := new Node_List;
Into.Children.Current := Into.Children.First'Access;
end if;
Append (Into.Children.all, Node);
end if;
end Append;
-- ------------------------------
-- Append a node to the node list.
-- ------------------------------
procedure Append (Into : in out Node_List;
Node : in Node_Type_Access) is
Block : Node_List_Block_Access := Into.Current;
begin
if Block.Last = Block.Max then
Block.Next := new Node_List_Block (Block.Max * 2);
Block := Block.Next;
Into.Current := Block;
end if;
Block.Last := Block.Last + 1;
Block.List (Block.Last) := Node;
Into.Length := Into.Length + 1;
end Append;
-- ------------------------------
-- Finalize the node list to release the allocated memory.
-- ------------------------------
procedure Finalize (List : in out Node_List) is
procedure Free is
new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Node_List, Node_List_Access);
procedure Release (List : in Node_List_Block_Access);
procedure Free_Block (Block : in out Node_List_Block);
procedure Free_Block (Block : in out Node_List_Block) is
begin
for I in 1 .. Block.Last loop
if Block.List (I).Kind = N_TAG_START and then Block.List (I).Children /= null then
Finalize (Block.List (I).Children.all);
Free (Block.List (I).Children);
end if;
Free (Block.List (I));
end loop;
end Free_Block;
procedure Release (List : in Node_List_Block_Access) is
Next : Node_List_Block_Access := List;
Block : Node_List_Block_Access;
begin
while Next /= null loop
Block := Next;
Free_Block (Block.all);
Next := Next.Next;
Free (Block);
end loop;
end Release;
begin
Release (List.First.Next);
Free_Block (List.First);
end Finalize;
end Wiki.Nodes;
|
Update the Append procedure to take into account the new node types
|
Update the Append procedure to take into account the new node types
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
e202becc348ca38601437c1a412c561f5215e56c
|
src/wiki-streams-html-builders.adb
|
src/wiki-streams-html-builders.adb
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Streams.Html.Builders is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class);
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in Content'Range loop
declare
C : constant Wiki.Strings.WChar := Content (I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is
Count : constant Natural := Wiki.Strings.Length (Content);
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in 1 .. Count loop
declare
C : constant Wiki.Strings.WChar := Wiki.Strings.Element (Content, I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
end Start_Element;
procedure End_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
for I in Content'Range loop
Html_Output_Builder_Stream'Class (Stream).Write_Escape (Content (I));
end loop;
end Write_Wide_Text;
end Wiki.Streams.Html.Builders;
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Streams.Html.Builders is
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class);
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_Output_Builder_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
if Stream.Close_Start then
Stream.Write_Escape_Attribute (Name, Content);
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Stream : in out Html_Output_Builder_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is
Count : constant Natural := Wiki.Strings.Length (Content);
begin
if Stream.Close_Start then
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in 1 .. Count loop
declare
C : constant Wiki.Strings.WChar := Wiki.Strings.Element (Content, I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write_String (Name);
Stream.Close_Start := True;
end Start_Element;
procedure End_Element (Stream : in out Html_Output_Builder_Stream;
Name : in String) is
begin
if Stream.Close_Start then
Stream.Write (" />");
Stream.Close_Start := False;
else
Close_Current (Stream);
Stream.Write ("</");
Stream.Write_String (Name);
Stream.Write ('>');
end if;
end End_Element;
procedure Write_Wide_Text (Stream : in out Html_Output_Builder_Stream;
Content : in Wiki.Strings.WString) is
begin
Close_Current (Stream);
Stream.Write_Escape (Content);
end Write_Wide_Text;
end Wiki.Streams.Html.Builders;
|
Use the Write_Escape and Write_Escape_Attribute operations
|
Use the Write_Escape and Write_Escape_Attribute operations
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
01e66661021baf57dae9c8deeb006c69993e961a
|
regtests/util-dates-formats-tests.ads
|
regtests/util-dates-formats-tests.ads
|
-----------------------------------------------------------------------
-- util-dates-formats-tests - Test for date formats
-- Copyright (C) 2011, 2013, 2014, 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Dates.Formats.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Format (T : in out Test);
-- Test parsing a date using several formats and different locales.
procedure Test_Parse (T : in out Test);
-- Test the Get_Day_Start operation.
procedure Test_Get_Day_Start (T : in out Test);
-- Test the Get_Week_Start operation.
procedure Test_Get_Week_Start (T : in out Test);
-- Test the Get_Month_Start operation.
procedure Test_Get_Month_Start (T : in out Test);
-- Test the Get_Day_End operation.
procedure Test_Get_Day_End (T : in out Test);
-- Test the Get_Week_End operation.
procedure Test_Get_Week_End (T : in out Test);
-- Test the Get_Month_End operation.
procedure Test_Get_Month_End (T : in out Test);
-- Test the Split operation.
procedure Test_Split (T : in out Test);
-- Test the Append_Date operation
procedure Test_Append_Date (T : in out Test);
-- Test the ISO8601 operations.
procedure Test_ISO8601 (T : in out Test);
end Util.Dates.Formats.Tests;
|
-----------------------------------------------------------------------
-- util-dates-formats-tests - Test for date formats
-- Copyright (C) 2011, 2013, 2014, 2015, 2016, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Dates.Formats.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Format (T : in out Test);
-- Test parsing a date using several formats and different locales.
procedure Test_Parse (T : in out Test);
-- Test parsing a date using several formats and having several errors.
procedure Test_Parse_Error (T : in out Test);
-- Test the Get_Day_Start operation.
procedure Test_Get_Day_Start (T : in out Test);
-- Test the Get_Week_Start operation.
procedure Test_Get_Week_Start (T : in out Test);
-- Test the Get_Month_Start operation.
procedure Test_Get_Month_Start (T : in out Test);
-- Test the Get_Day_End operation.
procedure Test_Get_Day_End (T : in out Test);
-- Test the Get_Week_End operation.
procedure Test_Get_Week_End (T : in out Test);
-- Test the Get_Month_End operation.
procedure Test_Get_Month_End (T : in out Test);
-- Test the Split operation.
procedure Test_Split (T : in out Test);
-- Test the Append_Date operation
procedure Test_Append_Date (T : in out Test);
-- Test the ISO8601 operations.
procedure Test_ISO8601 (T : in out Test);
end Util.Dates.Formats.Tests;
|
Declare Test_Parse_Error procedure
|
Declare Test_Parse_Error procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a0c7c8d35d25b60580cd957edaeb15262afa590b
|
regtests/util-events-timers-tests.adb
|
regtests/util-events-timers-tests.adb
|
-----------------------------------------------------------------------
-- util-events-timers-tests -- Unit tests for timers
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Events.Timers.Tests is
use Util.Tests;
use type Ada.Real_Time.Time;
package Caller is new Util.Test_Caller (Test, "Events.Timers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled",
Test_Empty_Timer'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Process",
Test_Timer_Event'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat",
Test_Repeat_Timer'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat+Process",
Test_Many_Timers'Access);
end Add_Tests;
overriding
procedure Time_Handler (Sub : in out Test;
Event : in out Timer_Ref'Class) is
begin
Sub.Count := Sub.Count + 1;
if Sub.Repeat > 1 then
Sub.Repeat := Sub.Repeat - 1;
Event.Repeat (Ada.Real_Time.Milliseconds (1));
end if;
end Time_Handler;
-- -----------------------
-- Test empty timers.
-- -----------------------
procedure Test_Empty_Timer (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Deadline : Ada.Real_Time.Time;
begin
T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled");
T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value");
R.Cancel;
M.Process (Deadline);
T.Assert (Deadline = Ada.Real_Time.Time_Last,
"The Process operation returned invalid deadline");
end Test_Empty_Timer;
procedure Test_Timer_Event (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
delay until Deadline;
M.Process (Deadline);
Assert_Equals (T, 1, T.Count, "The timer handler was not called");
end Test_Timer_Event;
-- -----------------------
-- Test repeating timers.
-- -----------------------
procedure Test_Repeat_Timer (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
T.Count := 0;
T.Repeat := 5;
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
loop
delay until Deadline;
M.Process (Deadline);
exit when Deadline >= Now + Ada.Real_Time.Seconds (1);
end loop;
Assert_Equals (T, 5, T.Count, "The timer handler was not repeated");
end Test_Repeat_Timer;
-- -----------------------
-- Test executing several timers.
-- -----------------------
procedure Test_Many_Timers (T : in out Test) is
Timer_Count : constant Positive := 30;
type Timer_Ref_Array is array (1 .. Timer_Count) of Timer_Ref;
type Test_Ref_Array is array (1 .. Timer_Count) of aliased Test;
M : Timer_List;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
R : Timer_Ref_Array;
D : Test_Ref_Array;
Dt : Ada.Real_Time.Time_Span;
Count : Natural := 0;
begin
for I in R'Range loop
D (I).Count := 0;
D (I).Repeat := 4;
if I mod 2 = 0 then
Dt := Ada.Real_Time.Milliseconds (40);
else
Dt := Ada.Real_Time.Milliseconds (20);
end if;
M.Set_Timer (D (I)'Unchecked_Access, R (I), Start + Dt);
end loop;
loop
M.Process (Deadline);
exit when Deadline >= Start + Ada.Real_Time.Seconds (10);
Count := Count + 1;
delay until Deadline;
end loop;
-- Depending on the load we can have different values for Count.
Util.Tests.Assert (T, Count <= 8, "Count of Process");
Util.Tests.Assert (T, Count <= 4, "Count of Process");
for I in D'Range loop
Util.Tests.Assert_Equals (T, 4, D (I).Count, "Invalid count for timer at "
& Natural'Image (I) & " " & Natural'Image (Count));
end loop;
end Test_Many_Timers;
end Util.Events.Timers.Tests;
|
-----------------------------------------------------------------------
-- util-events-timers-tests -- Unit tests for timers
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Events.Timers.Tests is
use Util.Tests;
use type Ada.Real_Time.Time;
package Caller is new Util.Test_Caller (Test, "Events.Timers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled",
Test_Empty_Timer'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Process",
Test_Timer_Event'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat",
Test_Repeat_Timer'Access);
Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat+Process",
Test_Many_Timers'Access);
end Add_Tests;
overriding
procedure Time_Handler (Sub : in out Test;
Event : in out Timer_Ref'Class) is
begin
Sub.Count := Sub.Count + 1;
if Sub.Repeat > 1 then
Sub.Repeat := Sub.Repeat - 1;
Event.Repeat (Ada.Real_Time.Milliseconds (1));
end if;
end Time_Handler;
-- -----------------------
-- Test empty timers.
-- -----------------------
procedure Test_Empty_Timer (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Deadline : Ada.Real_Time.Time;
begin
T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled");
T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value");
R.Cancel;
M.Process (Deadline);
T.Assert (Deadline = Ada.Real_Time.Time_Last,
"The Process operation returned invalid deadline");
end Test_Empty_Timer;
procedure Test_Timer_Event (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
delay until Deadline;
M.Process (Deadline);
Assert_Equals (T, 1, T.Count, "The timer handler was not called");
end Test_Timer_Event;
-- -----------------------
-- Test repeating timers.
-- -----------------------
procedure Test_Repeat_Timer (T : in out Test) is
M : Timer_List;
R : Timer_Ref;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
Now : Ada.Real_Time.Time;
begin
T.Count := 0;
T.Repeat := 5;
for Retry in 1 .. 10 loop
M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10));
M.Process (Deadline);
Now := Ada.Real_Time.Clock;
exit when Now < Deadline;
end loop;
T.Assert (Now < Deadline, "The timer deadline is not correct");
loop
delay until Deadline;
M.Process (Deadline);
exit when Deadline >= Now + Ada.Real_Time.Seconds (1);
end loop;
Assert_Equals (T, 5, T.Count, "The timer handler was not repeated");
end Test_Repeat_Timer;
-- -----------------------
-- Test executing several timers.
-- -----------------------
procedure Test_Many_Timers (T : in out Test) is
Timer_Count : constant Positive := 30;
type Timer_Ref_Array is array (1 .. Timer_Count) of Timer_Ref;
type Test_Ref_Array is array (1 .. Timer_Count) of aliased Test;
M : Timer_List;
Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Deadline : Ada.Real_Time.Time;
R : Timer_Ref_Array;
D : Test_Ref_Array;
Dt : Ada.Real_Time.Time_Span;
Count : Natural := 0;
begin
for I in R'Range loop
D (I).Count := 0;
D (I).Repeat := 4;
if I mod 2 = 0 then
Dt := Ada.Real_Time.Milliseconds (40);
else
Dt := Ada.Real_Time.Milliseconds (20);
end if;
M.Set_Timer (D (I)'Unchecked_Access, R (I), Start + Dt);
end loop;
loop
M.Process (Deadline);
exit when Deadline >= Start + Ada.Real_Time.Seconds (10);
Count := Count + 1;
delay until Deadline;
end loop;
-- Depending on the load we can have different values for Count.
T.Assert (Count <= 8, "Count of Process");
T.Assert (Count >= 2, "Count of Process");
for I in D'Range loop
Util.Tests.Assert_Equals (T, 4, D (I).Count, "Invalid count for timer at "
& Natural'Image (I) & " " & Natural'Image (Count));
end loop;
end Test_Many_Timers;
end Util.Events.Timers.Tests;
|
Fix unit test
|
Fix unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1392e33aebe2de13af8d8e08a0f9ec133459ed0f
|
regtests/util-streams-texts-tests.adb
|
regtests/util-streams-texts-tests.adb
|
-----------------------------------------------------------------------
-- streams.files.tests -- Unit tests for buffered streams
-- Copyright (C) 2012, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
package body Util.Streams.Texts.Tests is
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Texts");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close",
Test_Read_Line'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a text stream.
-- ------------------------------
procedure Test_Read_Line (T : in out Test) is
Stream : aliased Files.File_Stream;
Reader : Util.Streams.Texts.Reader_Stream;
Count : Natural := 0;
begin
Stream.Open (Name => "Makefile", Mode => In_File);
Reader.Initialize (From => Stream'Unchecked_Access);
while not Reader.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Reader.Read_Line (Line);
Count := Count + 1;
end;
end loop;
Stream.Close;
T.Assert (Count > 100, "Too few lines read");
end Test_Read_Line;
end Util.Streams.Texts.Tests;
|
-----------------------------------------------------------------------
-- streams.files.tests -- Unit tests for buffered streams
-- Copyright (C) 2012, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
package body Util.Streams.Texts.Tests is
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Texts");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close",
Test_Read_Line'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a text stream.
-- ------------------------------
procedure Test_Read_Line (T : in out Test) is
Stream : aliased Files.File_Stream;
Reader : Util.Streams.Texts.Reader_Stream;
Count : Natural := 0;
begin
Stream.Open (Name => "Makefile", Mode => In_File);
Reader.Initialize (From => Stream'Access);
while not Reader.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Reader.Read_Line (Line);
Count := Count + 1;
end;
end loop;
Stream.Close;
T.Assert (Count > 100, "Too few lines read");
end Test_Read_Line;
end Util.Streams.Texts.Tests;
|
Replace Unchecked_Access by Access in stream initialization
|
Replace Unchecked_Access by Access in stream initialization
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a1fa3c49afa41cdb91e372e3e2069b7fdc760928
|
demo/square.adb
|
demo/square.adb
|
-- Simple Lumen demo/test program, using earliest incomplete library
--
-- Build with: gnatmake square
with Ada.Text_IO;
with Lumen.Window;
with Lumen.Events.Keys;
with Lumen.Joystick;
with GL;
with GLU;
procedure Square is
---------------------------------------------------------------------------
Win : Lumen.Window.Handle;
Event : Lumen.Events.Event_Data;
Stick : Lumen.Joystick.Handle;
Joy : Lumen.Joystick.Joystick_Event_Data;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in GL.GLsizei) is
use GL;
use GLU;
Aspect : GLdouble;
begin -- Set_View
-- Viewport dimensions
glViewport (0, 0, W, H);
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
if W <= H then
Aspect := GLdouble (H) / GLdouble (W);
gluOrtho2D (-2.0, 2.0, -2.0 * Aspect, 2.0 * Aspect);
else
Aspect := GLdouble (W) / GLdouble (H);
gluOrtho2D (-2.0 * Aspect, 2.0 * Aspect, -2.0, 2.0);
end if;
end Set_View;
---------------------------------------------------------------------------
package IIO is new Ada.Text_IO.Integer_IO (Lumen.Events.Key_Symbol);
---------------------------------------------------------------------------
begin -- Square
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Lumen.Window.Create (Win, Name => "Ooh, Square!", Animated => False,
Events => (Lumen.Window.Want_Key_Press => True, others => False));
Set_View (400, 400);
-- Try opening first joystick
Lumen.Joystick.Open (Stick);
-- Loop until user hits a key or clicks the window's Close button
Outer: loop
-- Process window events if there are any pending
while Lumen.Events.Pending (Win) > 0 loop
declare
use type Lumen.Events.Event_Type;
begin
Event := Lumen.Events.Next_Event (Win);
-- Exit when they destroy the window
exit Outer when Event.Which = Lumen.Events.Close_Window;
-- Check for keypresses
if Event.Which = Lumen.Events.Key_Press then
declare
use Ada.Text_IO;
use Lumen.Events;
begin
Put ("Got ");
IIO.Put (Event.Key_Data.Key, Width => 1, Base => 16);
if Event.Key_Data.Key_Type = Key_Graphic then
Put (" '" & To_Character (Event.Key_Data.Key) & "'");
end if;
New_Line;
exit Outer when
(Event.Key_Data.Key_Type = Key_Control and then To_Character (Event.Key_Data.Key) = ASCII.ESC) or
(Event.Key_Data.Key_Type = Key_Graphic and then To_Character (Event.Key_Data.Key) = 'q');
end;
end if;
-- If we were resized, adjust the viewport dimensions
if Event.Which = Lumen.Events.Resized then
Set_View (GL.GLsizei (Event.Resize_Data.Width), GL.GLsizei (Event.Resize_Data.Height));
end if;
end;
end loop;
-- Process joystick events if there are any pending
while Lumen.Joystick.Pending (Stick) > 0 loop
declare
use Ada.Text_IO;
use Lumen.Joystick;
begin
Joy := Next_Event (Stick);
case Joy.Which is
when Joystick_Button_Press =>
Put_Line ("Button" & Positive'Image (Joy.Number) & " press");
when Joystick_Button_Release =>
Put_Line ("Button" & Positive'Image (Joy.Number) & " release");
when Joystick_Axis_Change =>
Put_Line ("Axis" & Positive'Image (Joy.Number) & " --> " & Integer'Image (Joy.Axis_Value));
end case;
end;
end loop;
-- Do our drawing
declare
use GL;
begin
glClearColor (0.0, 0.0, 0.0, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glBegin (GL_POLYGON);
begin
glVertex2f (-0.5, -0.5);
glVertex2f (-0.5, 0.5);
glVertex2f (0.5, 0.5);
glVertex2f (0.5, -0.5);
end;
glEnd;
glRotated (20.0, 0.0, 0.0, 1.0);
glFlush;
delay 0.25;
end;
end loop Outer;
end Square;
|
-- Simple Lumen demo/test program, using earliest incomplete library
--
-- Build with: gnatmake square
with Ada.Text_IO;
with Lumen.Window;
with Lumen.Events.Keys;
with Lumen.Joystick;
with GL;
with GLU;
procedure Square is
---------------------------------------------------------------------------
Win : Lumen.Window.Handle;
Event : Lumen.Events.Event_Data;
Have_JS : Boolean;
Stick : Lumen.Joystick.Handle;
Joy : Lumen.Joystick.Joystick_Event_Data;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in GL.GLsizei) is
use GL;
use GLU;
Aspect : GLdouble;
begin -- Set_View
-- Viewport dimensions
glViewport (0, 0, W, H);
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
if W <= H then
Aspect := GLdouble (H) / GLdouble (W);
gluOrtho2D (-2.0, 2.0, -2.0 * Aspect, 2.0 * Aspect);
else
Aspect := GLdouble (W) / GLdouble (H);
gluOrtho2D (-2.0 * Aspect, 2.0 * Aspect, -2.0, 2.0);
end if;
end Set_View;
---------------------------------------------------------------------------
package IIO is new Ada.Text_IO.Integer_IO (Lumen.Events.Key_Symbol);
---------------------------------------------------------------------------
begin -- Square
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Lumen.Window.Create (Win, Name => "Ooh, Square!", Animated => False,
Events => (Lumen.Window.Want_Key_Press => True, others => False));
Set_View (400, 400);
-- Try opening first joystick
begin
Lumen.Joystick.Open (Stick);
Have_JS := True;
exception
when others =>
Ada.Text_IO.Put_Line ("You don't seem to have a joystick. Too bad!");
Have_JS := False;
end;
-- Loop until user hits a key or clicks the window's Close button
Outer: loop
-- Process window events if there are any pending
while Lumen.Events.Pending (Win) > 0 loop
declare
use type Lumen.Events.Event_Type;
begin
Event := Lumen.Events.Next_Event (Win);
-- Exit when they destroy the window
exit Outer when Event.Which = Lumen.Events.Close_Window;
-- Check for keypresses
if Event.Which = Lumen.Events.Key_Press then
declare
use Ada.Text_IO;
use Lumen.Events;
begin
Put ("Got ");
IIO.Put (Event.Key_Data.Key, Width => 1, Base => 16);
if Event.Key_Data.Key_Type = Key_Graphic then
Put (" '" & To_Character (Event.Key_Data.Key) & "'");
end if;
New_Line;
exit Outer when
(Event.Key_Data.Key_Type = Key_Control and then To_Character (Event.Key_Data.Key) = ASCII.ESC) or
(Event.Key_Data.Key_Type = Key_Graphic and then To_Character (Event.Key_Data.Key) = 'q');
end;
end if;
-- If we were resized, adjust the viewport dimensions
if Event.Which = Lumen.Events.Resized then
Set_View (GL.GLsizei (Event.Resize_Data.Width), GL.GLsizei (Event.Resize_Data.Height));
end if;
end;
end loop;
-- Process joystick events if there are any pending
if Have_JS then
while Lumen.Joystick.Pending (Stick) > 0 loop
declare
use Ada.Text_IO;
use Lumen.Joystick;
begin
Joy := Next_Event (Stick);
case Joy.Which is
when Joystick_Button_Press =>
Put_Line ("Button" & Positive'Image (Joy.Number) & " press");
when Joystick_Button_Release =>
Put_Line ("Button" & Positive'Image (Joy.Number) & " release");
when Joystick_Axis_Change =>
Put_Line ("Axis" & Positive'Image (Joy.Number) & " --> " & Integer'Image (Joy.Axis_Value));
end case;
end;
end loop;
end if;
-- Do our drawing
declare
use GL;
begin
glClearColor (0.0, 0.0, 0.0, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glBegin (GL_POLYGON);
begin
glVertex2f (-0.5, -0.5);
glVertex2f (-0.5, 0.5);
glVertex2f (0.5, 0.5);
glVertex2f (0.5, -0.5);
end;
glEnd;
glRotated (20.0, 0.0, 0.0, 1.0);
glFlush;
delay 0.25;
end;
end loop Outer;
end Square;
|
Allow demo to be run without a joystick
|
Allow demo to be run without a joystick
|
Ada
|
isc
|
darkestkhan/lumen,darkestkhan/lumen2
|
cd232f0eb14f4fb6ea2f2ab662aeb2aa4f5d6ed3
|
awa/src/awa-events-configs.ads
|
awa/src/awa-events-configs.ads
|
-----------------------------------------------------------------------
-- awa-events-configs -- Event configuration
-- 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.Objects;
with Util.Serialize.IO.XML;
with EL.Expressions;
with EL.Beans;
with EL.Contexts;
with ADO.Sessions;
with AWA.Events.Queues;
with AWA.Events.Services;
package AWA.Events.Configs is
-- ------------------------------
-- Event Config Controller
-- ------------------------------
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Queue : AWA.Events.Queues.Queue_Ref;
Queue_Type : Util.Beans.Objects.Object;
Prop_Name : Util.Beans.Objects.Object;
Params : EL.Beans.Param_Vectors.Vector;
Priority : Integer;
Count : Integer;
Manager : AWA.Events.Services.Event_Manager_Access;
Action : EL.Expressions.Method_Expression;
Properties : EL.Beans.Param_Vectors.Vector;
Context : EL.Contexts.ELContext_Access;
Session : ADO.Sessions.Session;
Match : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Controller_Config_Access is access all Controller_Config;
type Config_Fields is (FIELD_ON_EVENT, FIELD_NAME, FIELD_QUEUE_NAME, FIELD_ACTION,
FIELD_PROPERTY_NAME, FIELD_QUEUE, FIELD_TYPE,
FIELD_PROPERTY_VALUE,
FIELD_DISPATCHER, FIELD_DISPATCHER_QUEUE, FIELD_DISPATCHER_PRIORITY,
FIELD_DISPATCHER_COUNT);
-- Set the configuration value identified by <b>Value</b> after having parsed
-- the element identified by <b>Field</b>.
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- Setup the XML parser to read the <b>queue</b> and <b>on-event</b> description.
-- For example:
--
-- <dispatcher name="async">
-- <queue name="async"/>
-- <queue name="persist"/>
-- <count>4</count>
-- <priority>10</priority>
-- </dispatcher>
--
-- <queue name="async" type="fifo">
-- <property name="size">254</property>
-- </queue>
--
-- <queue name="defer" type="persist">
-- </queue>
--
-- <on-event name="create-user" queue="async">
-- <action>#{mail.send}</action>
-- <property name="user">#{event.name}</property>
-- <property name="template">mail/welcome.xhtml</property>
-- </on-event>
--
-- This defines an event action called when the <b>create-user</b> event is posted.
-- The Ada bean <b>mail</b> is created and is populated with the <b>user</b> and
-- <b>template</b> properties. The Ada bean action method <b>send</b> is called.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in AWA.Events.Services.Event_Manager_Access;
Context : in EL.Contexts.ELContext_Access;
package Reader_Config is
Config : aliased Controller_Config;
end Reader_Config;
end AWA.Events.Configs;
|
-----------------------------------------------------------------------
-- awa-events-configs -- Event configuration
-- Copyright (C) 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Serialize.Mappers;
with EL.Expressions;
with EL.Beans;
with EL.Contexts;
with ADO.Sessions;
with AWA.Events.Queues;
with AWA.Events.Services;
package AWA.Events.Configs is
-- ------------------------------
-- Event Config Controller
-- ------------------------------
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Queue : AWA.Events.Queues.Queue_Ref;
Queue_Type : Util.Beans.Objects.Object;
Prop_Name : Util.Beans.Objects.Object;
Params : EL.Beans.Param_Vectors.Vector;
Priority : Integer;
Count : Integer;
Manager : AWA.Events.Services.Event_Manager_Access;
Action : EL.Expressions.Method_Expression;
Properties : EL.Beans.Param_Vectors.Vector;
Context : EL.Contexts.ELContext_Access;
Session : ADO.Sessions.Session;
Match : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Controller_Config_Access is access all Controller_Config;
type Config_Fields is (FIELD_ON_EVENT, FIELD_NAME, FIELD_QUEUE_NAME, FIELD_ACTION,
FIELD_PROPERTY_NAME, FIELD_QUEUE, FIELD_TYPE,
FIELD_PROPERTY_VALUE,
FIELD_DISPATCHER, FIELD_DISPATCHER_QUEUE, FIELD_DISPATCHER_PRIORITY,
FIELD_DISPATCHER_COUNT);
-- Set the configuration value identified by <b>Value</b> after having parsed
-- the element identified by <b>Field</b>.
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- Setup the XML parser to read the <b>queue</b> and <b>on-event</b> description.
-- For example:
--
-- <dispatcher name="async">
-- <queue name="async"/>
-- <queue name="persist"/>
-- <count>4</count>
-- <priority>10</priority>
-- </dispatcher>
--
-- <queue name="async" type="fifo">
-- <property name="size">254</property>
-- </queue>
--
-- <queue name="defer" type="persist">
-- </queue>
--
-- <on-event name="create-user" queue="async">
-- <action>#{mail.send}</action>
-- <property name="user">#{event.name}</property>
-- <property name="template">mail/welcome.xhtml</property>
-- </on-event>
--
-- This defines an event action called when the <b>create-user</b> event is posted.
-- The Ada bean <b>mail</b> is created and is populated with the <b>user</b> and
-- <b>template</b> properties. The Ada bean action method <b>send</b> is called.
generic
Mapper : in out Util.Serialize.Mappers.Processing;
Manager : in AWA.Events.Services.Event_Manager_Access;
Context : in EL.Contexts.ELContext_Access;
package Reader_Config is
Config : aliased Controller_Config;
end Reader_Config;
end AWA.Events.Configs;
|
Update the Prepare_Config to use the new parser/mapper interface
|
Update the Prepare_Config to use the new parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
9513566956cf2c2e5d1bd02e889e50793f6b599c
|
src/wiki-utils.ads
|
src/wiki-utils.ads
|
-----------------------------------------------------------------------
-- wiki-utils -- Wiki utility operations
-- 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 Wiki.Utils is
-- Render the wiki text according to the wiki syntax in HTML into a string.
function To_Html (Text : in Wide_Wide_String;
Syntax : in Wiki.Wiki_Syntax) return String;
-- 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 Wide_Wide_String;
Syntax : in Wiki.Wiki_Syntax) return String;
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.Strings;
package 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;
-- 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;
end Wiki.Utils;
|
Use the Wiki.Strings.WString type
|
Use the Wiki.Strings.WString type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
b4b57b56ae083803c64adaacb9e70d12defe670c
|
0005.adb
|
0005.adb
|
----------------------------------------------------------------------
-- Ada for POSIX (AdaFPX)
----------------------------------------------------------------------
-- Warren W. Gay VE3WWG Tue Dec 3 18:49:48 2013
--
-- This is generated source code. Edit at your own risk.
package body Posix is
function C_Last(C_String: String) return Natural is
begin
for X in C_String'Range loop
if Character'Pos(C_String(X)) = 0 then
return Natural(X-1);
end if;
end loop;
return C_String'Last;
end C_Last;
function To_Count(Status: ssize_t) return Natural is
begin
if Status <= 0 then
return 0;
else
return Natural(Status);
end if;
end To_Count;
pragma Inline(To_Count);
function To_Count(Status: int_t) return Natural is
begin
if Status <= 0 then
return 0;
else
return Natural(Status);
end if;
end To_Count;
pragma Inline(To_Count);
function C_Error(Ret_Val: int_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
if Ret_Val >= 0 then
return 0;
else
return c_errno;
end if;
end C_Error;
pragma Inline(C_Error);
function C_Error(Ret_Val: ssize_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
if Ret_Val >= 0 then
return 0;
else
return c_errno;
end if;
end C_Error;
pragma Inline(C_Error);
function C_Error(PID: pid_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
if PID /= -1 then
return 0;
else
return c_errno;
end if;
end C_Error;
pragma Inline(C_Error);
function C_Error(Ret_Val: clock_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
pragma Warnings(Off,"condition is always False");
if Ret_Val < 0 or else Ret_Val = clock_t'Last then
return c_errno;
else
return 0;
end if;
pragma Warnings(On,"condition is always False");
end C_Error;
function C_Error(Ret_Val: sig_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
if Ret_Val = SIG_ERR then
return c_errno;
else
return 0;
end if;
end C_Error;
function C_String(Ada_String: String) return String is
T : String(Ada_String'First..Ada_String'Last+1);
begin
T(T'First..T'Last-1) := Ada_String;
T(T'Last) := Character'Val(0);
return T;
end C_String;
function Ada_String(C_String: String) return String is
begin
for X in C_String'Range loop
if Character'Pos(C_String(X)) = 0 then
return C_String(C_String'First..X-1);
end if;
end loop;
return C_String;
end Ada_String;
function Pos_PID(Status: int_t) return pid_t is
begin
if Status >= 0 then
return pid_t(Status);
else
return 0;
end if;
end Pos_PID;
pragma Inline(Pos_PID);
function Neg_PID(Status: int_t) return pid_t is
begin
if Status < 0 then
return pid_t(-Status);
else
return 0;
end if;
end Neg_PID;
pragma Inline(Neg_PID);
function Argv_Length(Argvs: String) return Natural is
Count : Natural := 0;
begin
for X in Argvs'Range loop
if Character'Pos(Argvs(x)) = 0 then
Count := Count + 1;
end if;
end loop;
return Count + 1;
end Argv_Length;
function Argv_Length(Argv: argv_array) return Natural is
use System;
begin
for X in Argv'Range loop
if Argv(X) = System.Null_Address then
return X - Argv'First;
end if;
end loop;
return Argv'Length;
end Argv_Length;
procedure Find_Nul(S: String; X: out Natural; Found: out Boolean) is
begin
for Y in S'Range loop
if Character'Pos(S(Y)) = 0 then
X := Y;
Found := True;
end if;
end loop;
X := S'Last;
Found := False;
end Find_Nul;
function To_Argv(Argvs: String) return argv_array is
Count : constant Natural := Argv_Length(Argvs);
X : Natural := Argvs'First;
Y : Natural;
Found : Boolean;
begin
declare
Argv : argv_array(0..Count-1);
Arg_X : Natural := Argv'First;
begin
while X <= Argvs'Last loop
Find_Nul(Argvs(X..Argv'Last),Y,Found);
exit when not Found;
Argv(Arg_X) := Argvs(X)'Address;
Arg_X := Arg_X + 1;
X := Y + 1;
end loop;
Argv(Arg_X) := System.Null_Address;
return Argv;
end;
end To_Argv;
procedure To_Argv(Argvs: String; Argv: out argv_array) is
Count : Natural := Argv_Length(Argvs);
Arg_X : Natural := Argv'First;
C : Natural := 0;
X : Natural := Argvs'First;
Y : Natural;
Found : Boolean;
begin
pragma Assert(Argv'Length>1);
if Count > Argv'Length then
Count := Argv'Length - 1;
end if;
while C < Count and X <= Argvs'Last loop
Find_Nul(Argvs(X..Argv'Last),Y,Found);
exit when not Found;
Argv(Arg_X) := Argvs(X)'Address;
Arg_X := Arg_X + 1;
X := Y + 1;
C := C + 1;
end loop;
Argv(Arg_X) := System.Null_Address;
end To_Argv;
function To_Clock(Ticks: clock_t) return clock_t is
begin
pragma Warnings(Off,"condition is always False");
if Ticks < 0 or else Ticks = clock_t'Last then
return 0;
else
return Ticks;
end if;
pragma Warnings(On,"condition is always False");
end To_Clock;
|
----------------------------------------------------------------------
-- Ada for POSIX (AdaFPX)
----------------------------------------------------------------------
-- Warren W. Gay VE3WWG Tue Dec 3 18:49:48 2013
--
-- This is generated source code. Edit at your own risk.
package body Posix is
function C_Last(C_String: String) return Natural is
begin
for X in C_String'Range loop
if Character'Pos(C_String(X)) = 0 then
return Natural(X-1);
end if;
end loop;
return C_String'Last;
end C_Last;
function To_Count(Status: ssize_t) return Natural is
begin
if Status <= 0 then
return 0;
else
return Natural(Status);
end if;
end To_Count;
pragma Inline(To_Count);
function To_Count(Status: int_t) return Natural is
begin
if Status <= 0 then
return 0;
else
return Natural(Status);
end if;
end To_Count;
pragma Inline(To_Count);
function C_Error(Ret_Val: int_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
if Ret_Val >= 0 then
return 0;
else
return c_errno;
end if;
end C_Error;
pragma Inline(C_Error);
function C_Error(Ret_Val: ssize_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
if Ret_Val >= 0 then
return 0;
else
return c_errno;
end if;
end C_Error;
pragma Inline(C_Error);
function C_Error(PID: pid_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
if PID /= -1 then
return 0;
else
return c_errno;
end if;
end C_Error;
pragma Inline(C_Error);
function C_Error(Ret_Val: clock_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
pragma Warnings(Off);
if Ret_Val < 0 or else Ret_Val = clock_t'Last then
return c_errno;
else
return 0;
end if;
pragma Warnings(On);
end C_Error;
function C_Error(Ret_Val: sig_t) return errno_t is
function c_errno return errno_t;
pragma Import(C,c_errno,"c_errno");
begin
if Ret_Val = SIG_ERR then
return c_errno;
else
return 0;
end if;
end C_Error;
function C_String(Ada_String: String) return String is
T : String(Ada_String'First..Ada_String'Last+1);
begin
T(T'First..T'Last-1) := Ada_String;
T(T'Last) := Character'Val(0);
return T;
end C_String;
function Ada_String(C_String: String) return String is
begin
for X in C_String'Range loop
if Character'Pos(C_String(X)) = 0 then
return C_String(C_String'First..X-1);
end if;
end loop;
return C_String;
end Ada_String;
function Pos_PID(Status: int_t) return pid_t is
begin
if Status >= 0 then
return pid_t(Status);
else
return 0;
end if;
end Pos_PID;
pragma Inline(Pos_PID);
function Neg_PID(Status: int_t) return pid_t is
begin
if Status < 0 then
return pid_t(-Status);
else
return 0;
end if;
end Neg_PID;
pragma Inline(Neg_PID);
function Argv_Length(Argvs: String) return Natural is
Count : Natural := 0;
begin
for X in Argvs'Range loop
if Character'Pos(Argvs(x)) = 0 then
Count := Count + 1;
end if;
end loop;
return Count + 1;
end Argv_Length;
function Argv_Length(Argv: argv_array) return Natural is
use System;
begin
for X in Argv'Range loop
if Argv(X) = System.Null_Address then
return X - Argv'First;
end if;
end loop;
return Argv'Length;
end Argv_Length;
procedure Find_Nul(S: String; X: out Natural; Found: out Boolean) is
begin
for Y in S'Range loop
if Character'Pos(S(Y)) = 0 then
X := Y;
Found := True;
end if;
end loop;
X := S'Last;
Found := False;
end Find_Nul;
function To_Argv(Argvs: String) return argv_array is
Count : constant Natural := Argv_Length(Argvs);
X : Natural := Argvs'First;
Y : Natural;
Found : Boolean;
begin
declare
Argv : argv_array(0..Count-1);
Arg_X : Natural := Argv'First;
begin
while X <= Argvs'Last loop
Find_Nul(Argvs(X..Argv'Last),Y,Found);
exit when not Found;
Argv(Arg_X) := Argvs(X)'Address;
Arg_X := Arg_X + 1;
X := Y + 1;
end loop;
Argv(Arg_X) := System.Null_Address;
return Argv;
end;
end To_Argv;
procedure To_Argv(Argvs: String; Argv: out argv_array) is
Count : Natural := Argv_Length(Argvs);
Arg_X : Natural := Argv'First;
C : Natural := 0;
X : Natural := Argvs'First;
Y : Natural;
Found : Boolean;
begin
pragma Assert(Argv'Length>1);
if Count > Argv'Length then
Count := Argv'Length - 1;
end if;
while C < Count and X <= Argvs'Last loop
Find_Nul(Argvs(X..Argv'Last),Y,Found);
exit when not Found;
Argv(Arg_X) := Argvs(X)'Address;
Arg_X := Arg_X + 1;
X := Y + 1;
C := C + 1;
end loop;
Argv(Arg_X) := System.Null_Address;
end To_Argv;
function To_Clock(Ticks: clock_t) return clock_t is
begin
pragma Warnings(Off);
if Ticks < 0 or else Ticks = clock_t'Last then
return 0;
else
return Ticks;
end if;
pragma Warnings(On);
end To_Clock;
|
Fix warnings for other gnat versions
|
Fix warnings for other gnat versions
|
Ada
|
lgpl-2.1
|
ve3wwg/adafpx,ve3wwg/adafpx
|
1f709fb47116fb658d6df91591c45142753fe995
|
src/sys/encoders/util-encoders-aes.ads
|
src/sys/encoders/util-encoders-aes.ads
|
-----------------------------------------------------------------------
-- util-encoders-aes -- AES encryption and decryption
-- 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.Streams;
with Interfaces;
-- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to
-- RFC3174 or [FIPS-180-1].
package Util.Encoders.AES is
type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR);
type Key_Type is private;
-- ------------------------------
-- ------------------------------
subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16);
type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32;
procedure Set_Encrypt_Key (Key : out Key_Type;
Data : in Ada.Streams.Stream_Element_Array);
procedure Set_Decrypt_Key (Key : out Key_Type;
Data : in Ada.Streams.Stream_Element_Array);
procedure Encrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array;
Output : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Key : in Key_Type);
procedure Decrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 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
-- an SHA-1 hash 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);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Encoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset);
-- Set the encryption key to use.
procedure Set_Key (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Mode : in AES_Mode := CBC);
private
use Interfaces;
type Block_Key is array (0 .. 59) of Unsigned_32;
type Key_Type is record
Key : Block_Key;
Rounds : Natural := 0;
end record;
type Encoder is new Util.Encoders.Transformer with record
IV : Word_Block_Type;
Key : Key_Type;
Mode : AES_Mode := CBC;
end record;
end Util.Encoders.AES;
|
-----------------------------------------------------------------------
-- util-encoders-aes -- AES encryption and decryption
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Interfaces;
-- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to
-- RFC3174 or [FIPS-180-1].
package Util.Encoders.AES is
use type Ada.Streams.Stream_Element_Offset;
type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR);
type Key_Type is private;
-- ------------------------------
-- ------------------------------
subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16);
type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32;
procedure Set_Encrypt_Key (Key : out Key_Type;
Data : in Ada.Streams.Stream_Element_Array)
with Pre => Data'Length = 16 or Data'Length = 24 or Data'Length = 32;
procedure Set_Decrypt_Key (Key : out Key_Type;
Data : in Ada.Streams.Stream_Element_Array);
procedure Encrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Word_Block_Type;
Output : out Word_Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array;
Output : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Key : in Key_Type);
procedure Decrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 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
-- an SHA-1 hash 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);
-- Finish encoding the input array.
overriding
procedure Finish (E : in out Encoder;
Into : in out Ada.Streams.Stream_Element_Array;
Last : in out Ada.Streams.Stream_Element_Offset)
with Pre => Into'Length >= Block_Type'Length,
Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length;
-- Set the encryption key to use.
procedure Set_Key (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Mode : in AES_Mode := CBC);
-- Set the encryption initialization vector before starting the encryption.
procedure Set_IV (E : in out Encoder;
IV : in Word_Block_Type);
private
use Interfaces;
type Block_Key is array (0 .. 59) of Unsigned_32;
type Key_Type is record
Key : Block_Key;
Rounds : Natural := 0;
end record;
type Encoder is new Util.Encoders.Transformer with record
IV : Word_Block_Type;
Key : Key_Type;
Mode : AES_Mode := CBC;
Data_Count : Ada.Streams.Stream_Element_Offset := 0;
Data : Block_Type;
end record;
end Util.Encoders.AES;
|
Add Set_IV procedure and add several post/pre conditions
|
Add Set_IV procedure and add several post/pre conditions
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.