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
|
---|---|---|---|---|---|---|---|---|---|
a39c2aa473e5b3c4f7c10987c39989d113f33bfc
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Controllers;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
-- ------------------------------
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
exit when Manager.Permissions (I) = null;
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with" clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug
-- but we have to use a temporary variable and do some type conversion...
declare
P : Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end loop;
Free (Manager.Permissions);
end if;
end Finalize;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Controllers;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
-- ------------------------------
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
exit when Manager.Permissions (I) = null;
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with" clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug
-- but we have to use a temporary variable and do some type conversion...
declare
P : Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end loop;
Free (Manager.Permissions);
end if;
end Finalize;
end Security.Policies;
|
Implement the new function Get_Policy_Index
|
Implement the new function Get_Policy_Index
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
0529f9e94846b65aabe7f3ab125f5cfba539f48c
|
tools/timekey.adb
|
tools/timekey.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2015, 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.Calendar;
with Ada.Command_Line;
with Ada.Text_IO;
with Natools.Time_IO.RFC_3339;
with Natools.Time_Keys;
procedure Timekey is
procedure Process (Line : in String);
-- Guess the type of Line and convert it to or from type.
procedure Process_Input;
-- Read lines from current input and process them.
Input_Processed : Boolean := False;
Empty : Boolean := True;
Verbose : Boolean := False;
procedure Process (Line : in String) is
begin
if Verbose then
Ada.Text_IO.Put (Line);
end if;
if Natools.Time_Keys.Is_Valid (Line) then
if Verbose then
Ada.Text_IO.Put (" => ");
end if;
Ada.Text_IO.Put_Line
(Natools.Time_IO.RFC_3339.Image
(Natools.Time_Keys.To_Time (Line), Duration'Aft, False));
elsif Natools.Time_IO.RFC_3339.Is_Valid (Line) then
if Verbose then
Ada.Text_IO.Put (" => ");
end if;
Ada.Text_IO.Put_Line
(Natools.Time_Keys.To_Key (Natools.Time_IO.RFC_3339.Value (Line)));
end if;
end Process;
procedure Process_Input is
begin
if Input_Processed then
return;
else
Input_Processed := True;
end if;
begin
loop
Process (Ada.Text_IO.Get_Line);
end loop;
exception
when Ada.Text_IO.End_Error => null;
end;
end Process_Input;
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
if Ada.Command_Line.Argument (I) = "-" then
Empty := False;
Process_Input;
elsif Ada.Command_Line.Argument (I) = "-v" then
Verbose := True;
else
Empty := False;
Process (Ada.Command_Line.Argument (I));
end if;
end loop;
if Empty then
declare
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
if Verbose then
Ada.Text_IO.Put
(Natools.Time_IO.RFC_3339.Image (Now, Duration'Aft, False)
& " => ");
end if;
Ada.Text_IO.Put_Line (Natools.Time_Keys.To_Key (Now));
end;
end if;
end Timekey;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Calendar;
with Ada.Command_Line;
with Ada.Text_IO;
with Natools.Time_IO.RFC_3339;
with Natools.Time_Keys;
procedure Timekey is
procedure Process (Line : in String);
-- Guess the type of Line and convert it to or from type.
procedure Process_Input;
-- Read lines from current input and process them.
Input_Processed : Boolean := False;
Empty : Boolean := True;
Verbose : Boolean := False;
procedure Process (Line : in String) is
begin
if Verbose then
Ada.Text_IO.Put (Line);
end if;
if Natools.Time_Keys.Is_Valid (Line) then
if Verbose then
Ada.Text_IO.Put (" => ");
end if;
Ada.Text_IO.Put_Line
(Natools.Time_IO.RFC_3339.Image
(Natools.Time_Keys.To_Time (Line), Duration'Aft, False));
elsif Natools.Time_IO.RFC_3339.Is_Valid (Line) then
if Verbose then
Ada.Text_IO.Put (" => ");
end if;
Ada.Text_IO.Put_Line
(Natools.Time_Keys.To_Key (Natools.Time_IO.RFC_3339.Value (Line)));
end if;
end Process;
procedure Process_Input is
begin
if Input_Processed then
return;
else
Input_Processed := True;
end if;
begin
loop
Process (Ada.Text_IO.Get_Line);
end loop;
exception
when Ada.Text_IO.End_Error => null;
end;
end Process_Input;
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
declare
Arg : constant String := Ada.Command_Line.Argument (I);
begin
if Arg = "-" then
Empty := False;
Process_Input;
elsif Arg = "-v" then
Verbose := True;
else
Empty := False;
Process (Arg);
end if;
end;
end loop;
if Empty then
declare
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
if Verbose then
Ada.Text_IO.Put
(Natools.Time_IO.RFC_3339.Image (Now, Duration'Aft, False)
& " => ");
end if;
Ada.Text_IO.Put_Line (Natools.Time_Keys.To_Key (Now));
end;
end if;
end Timekey;
|
refactor command-line argument processing
|
tools/timekey: refactor command-line argument processing
|
Ada
|
isc
|
faelys/natools
|
bc5587295bc0fb83a0820e59e65e4e6b9c8e8c7d
|
regtests/util-serialize-io-xml-tests.ads
|
regtests/util-serialize-io-xml-tests.ads
|
-----------------------------------------------------------------------
-- serialize-io-xml-tests -- Unit tests for XML serialization
-- 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 AUnit.Test_Suites;
with AUnit.Test_Fixtures;
package Util.Serialize.IO.XML.Tests is
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite);
type Test is new AUnit.Test_Fixtures.Test_Fixture with null record;
procedure Test_Parser (T : in out Test);
procedure Test_Writer (T : in out Test);
end Util.Serialize.IO.XML.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-xml-tests -- Unit tests for XML serialization
-- 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 AUnit.Test_Suites;
with AUnit.Test_Fixtures;
package Util.Serialize.IO.XML.Tests is
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite);
type Test is new AUnit.Test_Fixtures.Test_Fixture with null record;
-- Test XML de-serialization
procedure Test_Parser (T : in out Test);
-- Test XML serialization
procedure Test_Writer (T : in out Test);
end Util.Serialize.IO.XML.Tests;
|
Add comment
|
Add comment
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
1393cba037165e223560d9c63d6bd6fd3222a593
|
src/ado-objects-cache.ads
|
src/ado-objects-cache.ads
|
-----------------------------------------------------------------------
-- objects.cache -- Object cache
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Objects;
with Ada.Containers.Indefinite_Hashed_Sets;
-- The <b>ADO.Objects.Cache</b> holds a cache of object records.
-- The cache maintains a set of objects that were loaded for a given session.
--
-- The cache is not thread-safe. It is not intended to be shared directly.
package ADO.Objects.Cache is
type Object_Cache is limited private;
-- Insert the object in the cache.
-- The reference counter associated with the object is incremented.
procedure Insert (Cache : in out Object_Cache;
Object : in Object_Record_Access);
-- Insert the object in the cache
-- The reference counter associated with the object is incremented.
procedure Insert (Cache : in out Object_Cache;
Object : in Object_Ref'Class);
-- Check if the object is contained in the cache
function Contains (Cache : in Object_Cache;
Key : in Object_Key) return Boolean;
function Find (Cache : in Object_Cache;
Key : in Object_Key) return Object_Record_Access;
procedure Find (Cache : in Object_Cache;
Object : in out Object_Ref'Class;
Key : in Object_Key);
-- Remove the object from the cache. The reference counter associated
-- with the object is decremented.
-- Do nothing if the object is not in the cache.
procedure Remove (Cache : in out Object_Cache;
Object : in Object_Record_Access);
-- Remove the object from the cache.
-- Do nothing if the object is not in the cache.
procedure Remove (Cache : in out Object_Cache;
Object : in Object_Ref);
-- Remove the object from the cache.
-- Do nothing if the object is not in the cache.
procedure Remove (Cache : in out Object_Cache;
Object : in Object_Key);
-- Remove all object in the cache.
procedure Remove_All (Cache : in out Object_Cache);
private
use Ada.Containers;
-- The cache is a <b>Hashed_Set</b> in which the object record pointers
-- are stored. The hash and comparison methods are based on the object key
-- and object type.
function Hash (Item : Object_Record_Access) return Hash_Type;
-- Compare whether the two objects pointed to by Left and Right have the same
-- object key.
function Equivalent_Elements (Left, Right : Object_Record_Access)
return Boolean;
package Object_Set is new Indefinite_Hashed_Sets
(Element_Type => Object_Record_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Elements);
type Object_Cache is new Ada.Finalization.Limited_Controlled with record
Objects : Object_Set.Set;
end record;
-- Finalize the object cache by removing all entries
overriding
procedure Finalize (Cache : in out Object_Cache);
end ADO.Objects.Cache;
|
-----------------------------------------------------------------------
-- objects.cache -- Object cache
-- Copyright (C) 2009, 2010, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Containers.Indefinite_Hashed_Sets;
-- The <b>ADO.Objects.Cache</b> holds a cache of object records.
-- The cache maintains a set of objects that were loaded for a given session.
--
-- The cache is not thread-safe. It is not intended to be shared directly.
package ADO.Objects.Cache is
type Object_Cache is limited private;
-- Insert the object in the cache.
-- The reference counter associated with the object is incremented.
procedure Insert (Cache : in out Object_Cache;
Object : in Object_Record_Access);
-- Insert the object in the cache
-- The reference counter associated with the object is incremented.
procedure Insert (Cache : in out Object_Cache;
Object : in Object_Ref'Class);
-- Check if the object is contained in the cache
function Contains (Cache : in Object_Cache;
Key : in Object_Key) return Boolean;
function Find (Cache : in Object_Cache;
Key : in Object_Key) return Object_Record_Access;
procedure Find (Cache : in Object_Cache;
Object : in out Object_Ref'Class;
Key : in Object_Key);
-- Remove the object from the cache. The reference counter associated
-- with the object is decremented.
-- Do nothing if the object is not in the cache.
procedure Remove (Cache : in out Object_Cache;
Object : in Object_Record_Access);
-- Remove the object from the cache.
-- Do nothing if the object is not in the cache.
procedure Remove (Cache : in out Object_Cache;
Object : in Object_Ref);
-- Remove the object from the cache.
-- Do nothing if the object is not in the cache.
procedure Remove (Cache : in out Object_Cache;
Object : in Object_Key);
-- Remove all object in the cache.
procedure Remove_All (Cache : in out Object_Cache);
private
use Ada.Containers;
-- The cache is a <b>Hashed_Set</b> in which the object record pointers
-- are stored. The hash and comparison methods are based on the object key
-- and object type.
function Hash (Item : Object_Record_Access) return Hash_Type;
-- Compare whether the two objects pointed to by Left and Right have the same
-- object key.
function Equivalent_Elements (Left, Right : Object_Record_Access)
return Boolean;
package Object_Set is new Indefinite_Hashed_Sets
(Element_Type => Object_Record_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Elements);
type Object_Cache is new Ada.Finalization.Limited_Controlled with record
Objects : Object_Set.Set;
end record;
-- Finalize the object cache by removing all entries
overriding
procedure Finalize (Cache : in out Object_Cache);
end ADO.Objects.Cache;
|
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
|
Fix compilation warning with GCC 12: remove unused with clause for an ancestor
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
aaa376906c3a6522d019346deb1ace30f925a77b
|
awa/regtests/awa-users-tests.adb
|
awa/regtests/awa-users-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Test_Caller;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Tests.Helpers.Users;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
package body AWA.Users.Tests is
use ASF.Tests;
package Caller is new Util.Test_Caller (Test, "Users.Tests");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of user by simulating web requests.
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
AWA.Tests.Helpers.Users.Initialize (Principal);
Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "asdf");
Request.Set_Parameter ("password2", "asdf");
Request.Set_Parameter ("firstName", "joe");
Request.Set_Parameter ("lastName", "dalton");
Request.Set_Parameter ("register", "1");
Request.Set_Parameter ("register-button", "1");
Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
-- Now, get the access key and simulate a click on the validation link.
declare
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
Do_Get (Request, Reply, "/auth/validate.html?key=" & Key.Get_Access_Key,
"validate-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
end;
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Create_User;
procedure Test_Logout_User (T : in out Test) is
begin
null;
end Test_Logout_User;
-- ------------------------------
-- Test user authentication by simulating a web request.
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
AWA.Tests.Set_Application_Context;
AWA.Tests.Get_Application.Dump_Routes (Util.Log.INFO_LEVEL);
begin
AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]");
-- It sometimes happen that Joe's password is changed by another test.
-- Recover the password and make sure it is 'admin'.
exception
when others =>
T.Recover_Password ("[email protected]", "admin");
end;
Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Request.Set_Parameter ("login-button", "1");
Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Login_User;
-- ------------------------------
-- Run the recovery password process for the given user and change the password.
-- ------------------------------
procedure Recover_Password (T : in out Test;
Email : in String;
Password : in String) is
use type ASF.Principals.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("lost-password", "1");
Request.Set_Parameter ("lost-password-button", "1");
Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html");
ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html",
Reply, "Invalid redirect after lost password");
-- Now, get the access key and simulate a click on the reset password link.
declare
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Set_Application_Context;
AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Request.Set_Parameter ("password", Password);
Request.Set_Parameter ("reset-password", "1");
Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end;
end Recover_Password;
-- ------------------------------
-- Test the reset password by simulating web requests.
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
begin
T.Recover_Password ("[email protected]", "asf");
T.Recover_Password ("[email protected]", "admin");
end Test_Reset_Password_User;
end AWA.Users.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Test_Caller;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Tests.Helpers.Users;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Principals;
package body AWA.Users.Tests is
use ASF.Tests;
use type ASF.Principals.Principal_Access;
package Caller is new Util.Test_Caller (Test, "Users.Tests");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate",
Test_OAuth_Login'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of user by simulating web requests.
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
AWA.Tests.Helpers.Users.Initialize (Principal);
Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("password", "asdf");
Request.Set_Parameter ("password2", "asdf");
Request.Set_Parameter ("firstName", "joe");
Request.Set_Parameter ("lastName", "dalton");
Request.Set_Parameter ("register", "1");
Request.Set_Parameter ("register-button", "1");
Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
-- Now, get the access key and simulate a click on the validation link.
declare
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
Do_Get (Request, Reply, "/auth/validate.html?key=" & Key.Get_Access_Key,
"validate-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
end;
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Create_User;
procedure Test_Logout_User (T : in out Test) is
begin
null;
end Test_Logout_User;
-- ------------------------------
-- Test user authentication by simulating a web request.
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
AWA.Tests.Set_Application_Context;
AWA.Tests.Get_Application.Dump_Routes (Util.Log.INFO_LEVEL);
begin
AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]");
-- It sometimes happen that Joe's password is changed by another test.
-- Recover the password and make sure it is 'admin'.
exception
when others =>
T.Recover_Password ("[email protected]", "admin");
end;
Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
-- Check that the user is NOT logged.
T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("login", "1");
Request.Set_Parameter ("login-button", "1");
Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end Test_Login_User;
-- ------------------------------
-- Test OAuth access using a fake OAuth provider.
-- ------------------------------
procedure Test_OAuth_Login (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
Do_Get (Request, Reply, "/auth/auth/google", "oauth-google.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("id", "oauth-user-id-fake");
Request.Set_Parameter ("claimed_id", "oauth-user-claimed_id-fake");
Do_Get (Request, Reply, "/auth/[email protected]&"
& "id=oauth-user-id-fake&claimed_id=oauth-user-claimed-id-fake",
"oauth-verify.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
Util.Tests.Assert_Equals (T, "Oauth-user", Request.Get_User_Principal.Get_Name,
"Invalid user name after OAuth authentication");
end Test_OAuth_Login;
-- ------------------------------
-- Run the recovery password process for the given user and change the password.
-- ------------------------------
procedure Recover_Password (T : in out Test;
Email : in String;
Password : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response");
Request.Set_Parameter ("email", Email);
Request.Set_Parameter ("lost-password", "1");
Request.Set_Parameter ("lost-password-button", "1");
Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html");
ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html",
Reply, "Invalid redirect after lost password");
-- Now, get the access key and simulate a click on the reset password link.
declare
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
AWA.Tests.Set_Application_Context;
AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key);
T.Assert (not Key.Is_Null, "There is no access key associated with the user");
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Request.Set_Parameter ("password", Password);
Request.Set_Parameter ("reset-password", "1");
Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response");
-- Check that the user is logged and we have a user principal now.
T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined");
end;
end Recover_Password;
-- ------------------------------
-- Test the reset password by simulating web requests.
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
begin
T.Recover_Password ("[email protected]", "asf");
T.Recover_Password ("[email protected]", "admin");
end Test_Reset_Password_User;
end AWA.Users.Tests;
|
Implement the Test_OAuth_Login to check the OAuth authentication and verification
|
Implement the Test_OAuth_Login to check the OAuth authentication and verification
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1c2c4bc5325ee6777a6fd20b5dce7fcfe3ded1f4
|
awa/src/awa-components-wikis.adb
|
awa/src/awa-components-wikis.adb
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- 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 Util.Strings;
with Ada.Characters.Conversions;
with ASF.Contexts.Writer;
with ASF.Utils;
with Wiki.Render.Html;
with Wiki.Writers;
package body AWA.Components.Wikis is
WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record
Writer : ASF.Contexts.Writer.Response_Writer_Access;
end record;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String);
-- Write a single character to the string builder.
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character) is
begin
Writer.Writer.Write_Wide_Char (Char);
end Write;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write (Content);
end Write;
-- ------------------------------
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
-- ------------------------------
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Element (Name, Content);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.Start_Element (Name);
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.End_Element (Name);
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write_Wide_Text;
-- ------------------------------
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
-- ------------------------------
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Parsers.Wiki_Syntax_Type is
Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME,
Context => Context,
Default => "dotclear");
begin
if Format = "dotclear" then
return Wiki.Parsers.SYNTAX_DOTCLEAR;
elsif Format = "google" then
return Wiki.Parsers.SYNTAX_GOOGLE;
elsif Format = "phpbb" then
return Wiki.Parsers.SYNTAX_PHPBB;
elsif Format = "creole" then
return Wiki.Parsers.SYNTAX_CREOLE;
elsif Format = "mediawiki" then
return Wiki.Parsers.SYNTAX_MEDIA_WIKI;
else
return Wiki.Parsers.SYNTAX_MIX;
end if;
end Get_Wiki_Style;
-- ------------------------------
-- Get the links renderer that must be used to render image and page links.
-- ------------------------------
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Link_Renderer_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Link_Renderer_Bean'Class) then
return null;
else
return Link_Renderer_Bean'Class (Bean.all)'Access;
end if;
end Get_Links_Renderer;
-- ------------------------------
-- Render the wiki text
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class) is
use ASF.Contexts.Writer;
use type Wiki.Render.Link_Renderer_Access;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Html : aliased Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context);
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME);
Links : Wiki.Render.Link_Renderer_Access;
begin
Html.Writer := Writer;
Writer.Start_Element ("div");
UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer);
if not Util.Beans.Objects.Is_Empty (Value) then
Links := UI.Get_Links_Renderer (Context);
if Links /= null then
Renderer.Set_Link_Renderer (Links);
end if;
Renderer.Set_Writer (Html'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access,
Util.Beans.Objects.To_Wide_Wide_String (Value),
Format);
end if;
Writer.End_Element ("div");
end;
end Encode_Begin;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean is
use Ada.Characters.Conversions;
Pos : Positive := 1;
begin
if Length (Content) < Item'Length then
return False;
end if;
for I in Item'Range loop
if Item (I) /= To_Character (Element (Content, Pos)) then
return False;
end if;
Pos := Pos + 1;
end loop;
return True;
end Starts_With;
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String) is
begin
if Starts_With (Link, "http://") or Starts_With (Link, "https://") then
URI := Link;
else
URI := Prefix & Link;
end if;
end Make_Link;
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is
begin
Renderer.Make_Link (Link, Renderer.Image_Prefix, URI);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
begin
Renderer.Make_Link (Link, Renderer.Page_Prefix, URI);
Exists := True;
end Make_Page_Link;
begin
ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES);
end AWA.Components.Wikis;
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Characters.Conversions;
with ASF.Contexts.Writer;
with ASF.Utils;
with Wiki.Render.Html;
with Wiki.Writers;
package body AWA.Components.Wikis is
WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record
Writer : ASF.Contexts.Writer.Response_Writer_Access;
end record;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String);
-- Write a single character to the string builder.
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character) is
begin
Writer.Writer.Write_Wide_Char (Char);
end Write;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write (Content);
end Write;
-- ------------------------------
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
-- ------------------------------
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Element (Name, Content);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.Start_Element (Name);
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.End_Element (Name);
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write_Wide_Text;
-- ------------------------------
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
-- ------------------------------
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Parsers.Wiki_Syntax_Type is
Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME,
Context => Context,
Default => "dotclear");
begin
if Format = "dotclear" then
return Wiki.Parsers.SYNTAX_DOTCLEAR;
elsif Format = "google" then
return Wiki.Parsers.SYNTAX_GOOGLE;
elsif Format = "phpbb" then
return Wiki.Parsers.SYNTAX_PHPBB;
elsif Format = "creole" then
return Wiki.Parsers.SYNTAX_CREOLE;
elsif Format = "mediawiki" then
return Wiki.Parsers.SYNTAX_MEDIA_WIKI;
else
return Wiki.Parsers.SYNTAX_MIX;
end if;
end Get_Wiki_Style;
-- ------------------------------
-- Get the links renderer that must be used to render image and page links.
-- ------------------------------
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Link_Renderer_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Link_Renderer_Bean'Class) then
return null;
else
return Link_Renderer_Bean'Class (Bean.all)'Access;
end if;
end Get_Links_Renderer;
-- ------------------------------
-- Render the wiki text
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class) is
use ASF.Contexts.Writer;
use type Wiki.Render.Link_Renderer_Access;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Html : aliased Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context);
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME);
Links : Wiki.Render.Link_Renderer_Access;
begin
Html.Writer := Writer;
Writer.Start_Element ("div");
UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer);
if not Util.Beans.Objects.Is_Empty (Value) then
Links := UI.Get_Links_Renderer (Context);
if Links /= null then
Renderer.Set_Link_Renderer (Links);
end if;
Renderer.Set_Writer (Html'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access,
Util.Beans.Objects.To_Wide_Wide_String (Value),
Format);
end if;
Writer.End_Element ("div");
end;
end Encode_Begin;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean is
use Ada.Characters.Conversions;
Pos : Positive := 1;
begin
if Length (Content) < Item'Length then
return False;
end if;
for I in Item'Range loop
if Item (I) /= To_Character (Element (Content, Pos)) then
return False;
end if;
Pos := Pos + 1;
end loop;
return True;
end Starts_With;
-- ------------------------------
-- Return true if the link is an absolute link.
-- ------------------------------
function Is_Link_Absolute (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String) return Boolean is
begin
return Starts_With (Link, "http://") or Starts_With (Link, "https://");
end Is_Link_Absolute;
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String) is
begin
if Renderer.Is_Link_Absolute (Link) then
URI := Link;
else
URI := Prefix & Link;
end if;
end Make_Link;
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is
begin
Renderer.Make_Link (Link, Renderer.Image_Prefix, URI);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
begin
Renderer.Make_Link (Link, Renderer.Page_Prefix, URI);
Exists := True;
end Make_Page_Link;
begin
ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES);
end AWA.Components.Wikis;
|
Implement Is_Link_Absolute function and use it to check if we must use the prefix or not
|
Implement Is_Link_Absolute function and use it to check if we must use the prefix or not
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5e139aab80f45317816bfe69750208e48673c388
|
awa/src/awa-components-wikis.adb
|
awa/src/awa-components-wikis.adb
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 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.Strings;
with Ada.Characters.Conversions;
with ASF.Contexts.Writer;
with ASF.Utils;
with Wiki.Documents;
with Wiki.Parsers;
with Wiki.Helpers;
with Wiki.Render.Html;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Filters.Autolink;
with Wiki.Filters.Variables;
with Wiki.Streams.Html;
package body AWA.Components.Wikis is
WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record
Writer : ASF.Contexts.Writer.Response_Writer_Access;
end record;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String);
-- Write a single character to the string builder.
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wiki.Strings.WString);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Raw (Content);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character) is
begin
Writer.Writer.Write_Wide_Char (Char);
end Write;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.Start_Element (Name);
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.End_Element (Name);
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write_Wide_Text;
-- ------------------------------
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
-- ------------------------------
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Wiki_Syntax is
Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME,
Context => Context,
Default => "dotclear");
begin
if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then
return Wiki.SYNTAX_DOTCLEAR;
elsif Format = "google" then
return Wiki.SYNTAX_GOOGLE;
elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then
return Wiki.SYNTAX_PHPBB;
elsif Format = "creole" or Format = "FORMAT_CREOLE" then
return Wiki.SYNTAX_CREOLE;
elsif Format = "markdown" or Format = "FORMAT_MARKDOWN" then
return Wiki.SYNTAX_MARKDOWN;
elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then
return Wiki.SYNTAX_MEDIA_WIKI;
else
return Wiki.SYNTAX_MIX;
end if;
end Get_Wiki_Style;
-- ------------------------------
-- Get the links renderer that must be used to render image and page links.
-- ------------------------------
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Links.Link_Renderer_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Link_Renderer_Bean'Class) then
return null;
else
return Link_Renderer_Bean'Class (Bean.all)'Access;
end if;
end Get_Links_Renderer;
-- ------------------------------
-- Get the plugin factory that must be used by the Wiki parser.
-- ------------------------------
function Get_Plugin_Factory (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Plugins.Plugin_Factory_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, PLUGINS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Wiki.Plugins.Plugin_Factory'Class) then
return null;
else
return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access;
end if;
end Get_Plugin_Factory;
-- ------------------------------
-- Render the wiki text
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class) is
use ASF.Contexts.Writer;
use type Wiki.Render.Links.Link_Renderer_Access;
use type Wiki.Plugins.Plugin_Factory_Access;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Html : aliased Html_Writer_Type;
Doc : Wiki.Documents.Document;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Vars : aliased Wiki.Filters.Variables.Variable_Filter;
Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context);
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME);
Links : Wiki.Render.Links.Link_Renderer_Access;
Plugins : Wiki.Plugins.Plugin_Factory_Access;
Engine : Wiki.Parsers.Parser;
begin
Html.Writer := Writer;
Writer.Start_Element ("div");
UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer);
if not Util.Beans.Objects.Is_Empty (Value) then
Plugins := UI.Get_Plugin_Factory (Context);
if Plugins /= null then
Engine.Set_Plugin_Factory (Plugins);
end if;
Links := UI.Get_Links_Renderer (Context);
if Links /= null then
Renderer.Set_Link_Renderer (Links);
end if;
Engine.Add_Filter (Autolink'Unchecked_Access);
Engine.Add_Filter (Vars'Unchecked_Access);
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Format);
Engine.Parse (Util.Beans.Objects.To_String (Value), Doc);
Renderer.Set_Output_Stream (Html'Unchecked_Access);
Renderer.Set_Render_TOC (UI.Get_Attribute (TOC_NAME, Context, False));
Renderer.Render (Doc);
end if;
Writer.End_Element ("div");
end;
end Encode_Begin;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = IMAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Image_Prefix);
elsif Name = PAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Page_Prefix);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = IMAGE_PREFIX_ATTR then
From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
elsif Name = PAGE_PREFIX_ATTR then
From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
end if;
end Set_Value;
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean is
use Ada.Characters.Conversions;
Pos : Positive := 1;
begin
if Length (Content) < Item'Length then
return False;
end if;
for I in Item'Range loop
if Item (I) /= To_Character (Element (Content, Pos)) then
return False;
end if;
Pos := Pos + 1;
end loop;
return True;
end Starts_With;
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String) is
pragma Unreferenced (Renderer);
begin
if Wiki.Helpers.Is_Url (Link) then
URI := To_Unbounded_Wide_Wide_String (Link);
else
URI := Prefix & Link;
end if;
end Make_Link;
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : in out Natural;
Height : in out Natural) is
begin
Renderer.Make_Link (Link, Renderer.Image_Prefix, URI);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
begin
Renderer.Make_Link (Link, Renderer.Page_Prefix, URI);
Exists := True;
end Make_Page_Link;
begin
ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES);
end AWA.Components.Wikis;
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Characters.Conversions;
with ASF.Contexts.Writer;
with ASF.Utils;
with Wiki.Documents;
with Wiki.Parsers;
with Wiki.Helpers;
with Wiki.Render.Html;
with Wiki.Filters.Html;
with Wiki.Filters.TOC;
with Wiki.Filters.Autolink;
with Wiki.Filters.Variables;
with Wiki.Streams.Html;
package body AWA.Components.Wikis is
WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record
Writer : ASF.Contexts.Writer.Response_Writer_Access;
end record;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String);
-- Write a single character to the string builder.
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wiki.Strings.WString);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Raw (Content);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character) is
begin
Writer.Writer.Write_Wide_Char (Char);
end Write;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.Start_Element (Name);
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.End_Element (Name);
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Wiki.Strings.WString) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write_Wide_Text;
-- ------------------------------
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
-- ------------------------------
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Wiki_Syntax is
Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME,
Context => Context,
Default => "dotclear");
begin
if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then
return Wiki.SYNTAX_DOTCLEAR;
elsif Format = "google" then
return Wiki.SYNTAX_GOOGLE;
elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then
return Wiki.SYNTAX_PHPBB;
elsif Format = "creole" or Format = "FORMAT_CREOLE" then
return Wiki.SYNTAX_CREOLE;
elsif Format = "markdown" or Format = "FORMAT_MARKDOWN" then
return Wiki.SYNTAX_MARKDOWN;
elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then
return Wiki.SYNTAX_MEDIA_WIKI;
elsif Format = "html" or Format = "FORMAT_HTML" then
return Wiki.SYNTAX_HTML;
else
return Wiki.SYNTAX_MIX;
end if;
end Get_Wiki_Style;
-- ------------------------------
-- Get the links renderer that must be used to render image and page links.
-- ------------------------------
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Links.Link_Renderer_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Link_Renderer_Bean'Class) then
return null;
else
return Link_Renderer_Bean'Class (Bean.all)'Access;
end if;
end Get_Links_Renderer;
-- ------------------------------
-- Get the plugin factory that must be used by the Wiki parser.
-- ------------------------------
function Get_Plugin_Factory (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Plugins.Plugin_Factory_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, PLUGINS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Wiki.Plugins.Plugin_Factory'Class) then
return null;
else
return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access;
end if;
end Get_Plugin_Factory;
-- ------------------------------
-- Render the wiki text
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class) is
use ASF.Contexts.Writer;
use type Wiki.Render.Links.Link_Renderer_Access;
use type Wiki.Plugins.Plugin_Factory_Access;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Html : aliased Html_Writer_Type;
Doc : Wiki.Documents.Document;
TOC : aliased Wiki.Filters.TOC.TOC_Filter;
Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Filter : aliased Wiki.Filters.Html.Html_Filter_Type;
Vars : aliased Wiki.Filters.Variables.Variable_Filter;
Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context);
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME);
Links : Wiki.Render.Links.Link_Renderer_Access;
Plugins : Wiki.Plugins.Plugin_Factory_Access;
Engine : Wiki.Parsers.Parser;
begin
Html.Writer := Writer;
Writer.Start_Element ("div");
UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer);
if not Util.Beans.Objects.Is_Empty (Value) then
Plugins := UI.Get_Plugin_Factory (Context);
if Plugins /= null then
Engine.Set_Plugin_Factory (Plugins);
end if;
Links := UI.Get_Links_Renderer (Context);
if Links /= null then
Renderer.Set_Link_Renderer (Links);
end if;
Engine.Add_Filter (Autolink'Unchecked_Access);
Engine.Add_Filter (Vars'Unchecked_Access);
Engine.Add_Filter (TOC'Unchecked_Access);
Engine.Add_Filter (Filter'Unchecked_Access);
Engine.Set_Syntax (Format);
Engine.Parse (Util.Beans.Objects.To_String (Value), Doc);
Renderer.Set_Output_Stream (Html'Unchecked_Access);
Renderer.Set_Render_TOC (UI.Get_Attribute (TOC_NAME, Context, False));
Renderer.Render (Doc);
end if;
Writer.End_Element ("div");
end;
end Encode_Begin;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = IMAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Image_Prefix);
elsif Name = PAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Page_Prefix);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = IMAGE_PREFIX_ATTR then
From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
elsif Name = PAGE_PREFIX_ATTR then
From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
end if;
end Set_Value;
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean is
use Ada.Characters.Conversions;
Pos : Positive := 1;
begin
if Length (Content) < Item'Length then
return False;
end if;
for I in Item'Range loop
if Item (I) /= To_Character (Element (Content, Pos)) then
return False;
end if;
Pos := Pos + 1;
end loop;
return True;
end Starts_With;
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String) is
pragma Unreferenced (Renderer);
begin
if Wiki.Helpers.Is_Url (Link) then
URI := To_Unbounded_Wide_Wide_String (Link);
else
URI := Prefix & Link;
end if;
end Make_Link;
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : in out Natural;
Height : in out Natural) is
begin
Renderer.Make_Link (Link, Renderer.Image_Prefix, URI);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
begin
Renderer.Make_Link (Link, Renderer.Page_Prefix, URI);
Exists := True;
end Make_Page_Link;
begin
ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES);
end AWA.Components.Wikis;
|
Fix Get_Wiki_Style to recognize and use the 'html' format
|
Fix Get_Wiki_Style to recognize and use the 'html' format
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
4e139d021fa8c42a1db2a5a16b0177e9308d5e44
|
src/el-beans-methods-proc_1.adb
|
src/el-beans-methods-proc_1.adb
|
-----------------------------------------------------------------------
-- EL.Beans.Methods.Proc_1 -- Procedure Binding with 1 argument
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body EL.Beans.Methods.Proc_1 is
use EL.Expressions;
-- ------------------------------
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
-- ------------------------------
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in Param1_Type;
Context : in EL.Contexts.ELContext'Class) is
Info : constant Method_Info := Method.Get_Method_Info (Context);
begin
if Info.Binding = null then
raise EL.Expressions.Invalid_Method with "Method not found";
end if;
-- If the binding has the wrong type, we are trying to invoke
-- a method with a different signature.
if not (Info.Binding.all in Binding'Class) then
raise EL.Expressions.Invalid_Method
with "Invalid signature for method '" & Info.Binding.Name.all & "'";
end if;
declare
Proxy : constant Binding_Access := Binding (Info.Binding.all)'Access;
begin
Proxy.Method (Info.Object, Param);
end;
end Execute;
-- ------------------------------
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
-- ------------------------------
package body Bind is
procedure Method_Access (O : access EL.Beans.Readonly_Bean'Class;
P1 : Param1_Type) is
Object : access Bean := Bean (O.all)'Access;
begin
Method (Object.all, P1);
end Method_Access;
end Bind;
end EL.Beans.Methods.Proc_1;
|
-----------------------------------------------------------------------
-- EL.Beans.Methods.Proc_1 -- Procedure Binding with 1 argument
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body EL.Beans.Methods.Proc_1 is
use EL.Expressions;
-- ------------------------------
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
-- ------------------------------
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in Param1_Type;
Context : in EL.Contexts.ELContext'Class) is
Info : constant Method_Info := Method.Get_Method_Info (Context);
begin
if Info.Binding = null then
raise EL.Expressions.Invalid_Method with "Method not found";
end if;
-- If the binding has the wrong type, we are trying to invoke
-- a method with a different signature.
if not (Info.Binding.all in Binding'Class) then
raise EL.Expressions.Invalid_Method
with "Invalid signature for method '" & Info.Binding.Name.all & "'";
end if;
declare
Proxy : constant Binding_Access := Binding (Info.Binding.all)'Access;
begin
Proxy.Method (Info.Object, Param);
end;
end Execute;
-- ------------------------------
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
-- ------------------------------
package body Bind is
procedure Method_Access (O : access EL.Beans.Readonly_Bean'Class;
P1 : Param1_Type) is
Object : constant access Bean := Bean (O.all)'Access;
begin
Method (Object.all, P1);
end Method_Access;
end Bind;
end EL.Beans.Methods.Proc_1;
|
Fix indentation and compilation warning
|
Fix indentation and compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
0e77e0d6a5e333a8744d6114882dd8e28ee69014
|
regtests/util-events-timers-tests.adb
|
regtests/util-events-timers-tests.adb
|
-----------------------------------------------------------------------
-- util-events-timers-tests -- Unit tests for timers
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with 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);
end Add_Tests;
overriding
procedure Time_Handler (Sub : in out Test;
Event : in out Timer_Ref'Class) is
begin
Sub.Count := Sub.Count + 1;
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");
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 : 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;
end Util.Events.Timers.Tests;
|
-----------------------------------------------------------------------
-- util-events-timers-tests -- Unit tests for timers
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.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);
end Add_Tests;
overriding
procedure Time_Handler (Sub : in out Test;
Event : in out Timer_Ref'Class) is
begin
Sub.Count := Sub.Count + 1;
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;
end Util.Events.Timers.Tests;
|
Add test for Time_Of_Event function
|
Add test for Time_Of_Event function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
88df830dd6b0fe995cc4426ad2d9229a24c803e7
|
samples/popen.adb
|
samples/popen.adb
|
-----------------------------------------------------------------------
-- pipe -- Print the GNAT version by using a pipe
-- 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.Text_IO;
with Ada.Strings.Unbounded;
with Util.Processes;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
procedure Popen is
Command : constant String := "gnatmake --version";
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Pipe.Open (Command, Util.Processes.READ);
Buffer.Initialize (Pipe'Access, 1024);
Buffer.Read (Content);
Pipe.Close;
if Pipe.Get_Exit_Status /= 0 then
Ada.Text_IO.Put_Line (Command & " exited with status "
& Integer'Image (Pipe.Get_Exit_Status));
return;
end if;
Ada.Text_IO.Put_Line ("Result: " & Ada.Strings.Unbounded.To_String (Content));
end Popen;
|
-----------------------------------------------------------------------
-- popen -- Print the GNAT version by using a pipe
-- Copyright (C) 2011, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Util.Processes;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
procedure Popen is
Command : constant String := "gnatmake --version";
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Pipe.Open (Command, Util.Processes.READ);
Buffer.Initialize (Pipe'Unchecked_Access, 1024);
Buffer.Read (Content);
Pipe.Close;
if Pipe.Get_Exit_Status /= 0 then
Ada.Text_IO.Put_Line (Command & " exited with status "
& Integer'Image (Pipe.Get_Exit_Status));
return;
end if;
Ada.Text_IO.Put_Line ("Result: " & Ada.Strings.Unbounded.To_String (Content));
end Popen;
|
Fix for GNAT 2021
|
Fix for GNAT 2021
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9b0b050d43e966f70cc243d91f01ba5b242962f2
|
mat/src/mat-types.adb
|
mat/src/mat-types.adb
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
package body MAT.Types is
-- ------------------------------
-- Return an hexadecimal string representation of the value.
-- ------------------------------
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String is
use type Interfaces.Unsigned_32;
Conversion : constant String (1 .. 16) := "0123456789ABCDEF";
S : String (1 .. Length) := (others => '0');
P : Uint32 := Value;
N : Uint32;
I : Positive := Length;
begin
while P /= 0 loop
N := P mod 16;
P := P / 16;
S (I) := Conversion (Natural (N + 1));
exit when I = 1;
I := I - 1;
end loop;
return S;
end Hex_Image;
-- ------------------------------
-- Format the target time to a printable representation.
-- ------------------------------
function Tick_Image (Value : in Target_Tick_Ref) return String is
use type Interfaces.Unsigned_64;
Sec : Interfaces.Unsigned_32 := Interfaces.Unsigned_32 (Interfaces.Shift_Right (Value, 32));
Usec : Interfaces.Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#);
begin
return Interfaces.Unsigned_32'Image (Sec) & "." & Interfaces.Unsigned_32'Image (Usec);
end Tick_Image;
end MAT.Types;
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
package body MAT.Types is
-- ------------------------------
-- Return an hexadecimal string representation of the value.
-- ------------------------------
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String is
use type Interfaces.Unsigned_32;
Conversion : constant String (1 .. 16) := "0123456789ABCDEF";
S : String (1 .. Length) := (others => '0');
P : Uint32 := Value;
N : Uint32;
I : Positive := Length;
begin
while P /= 0 loop
N := P mod 16;
P := P / 16;
S (I) := Conversion (Natural (N + 1));
exit when I = 1;
I := I - 1;
end loop;
return S;
end Hex_Image;
-- ------------------------------
-- Format the target time to a printable representation.
-- ------------------------------
function Tick_Image (Value : in Target_Tick_Ref) return String is
use Interfaces;
Sec : constant Unsigned_32 := Unsigned_32 (Interfaces.Shift_Right (Uint64 (Value), 32));
Usec : constant Unsigned_32 := Interfaces.Unsigned_32 (Value and 16#0ffffffff#);
Frac : constant String := Interfaces.Unsigned_32'Image (Usec);
Img : String (1 .. 6) := (others => '0');
begin
Img (Img'Last - Frac'Length + 2 .. Img'Last) := Frac (Frac'First + 1 .. Frac'Last);
return Interfaces.Unsigned_32'Image (Sec) & "." & Img;
end Tick_Image;
function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref is
use Interfaces;
Res : Target_Tick_Ref := Target_Tick_Ref (Uint64 (Left) - Uint64 (Right));
Usec1 : constant Unsigned_32 := Interfaces.Unsigned_32 (Left and 16#0ffffffff#);
Usec2 : constant Unsigned_32 := Interfaces.Unsigned_32 (Right and 16#0ffffffff#);
begin
if Usec1 < Usec2 then
Res := Res and 16#ffffffff00000000#;
Res := Target_Tick_Ref (Uint64 (Res) - 16#100000000#);
Res := Res or Target_Tick_Ref (Usec2 - Usec1);
end if;
return Res;
end "-";
end MAT.Types;
|
Fix the formatting for Tick_Ref
|
Fix the formatting for Tick_Ref
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
485682c4aef0972eb4a48c6128a9d0f092649241
|
mat/src/memory/mat-memory-targets.ads
|
mat/src/memory/mat-memory-targets.ads
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- 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 Util.Events;
with MAT.Frames;
with MAT.Readers;
with MAT.Memory.Events;
with MAT.Memory.Tools;
package MAT.Memory.Targets is
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
private
protected type Memory_Allocator is
-- 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);
-- 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);
-- 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);
-- 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);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Reader : MAT.Readers.Reader_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- 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 Util.Events;
with MAT.Frames;
with MAT.Readers;
with MAT.Memory.Events;
with MAT.Memory.Tools;
package MAT.Memory.Targets is
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
private
protected type Memory_Allocator is
-- 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);
-- 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);
-- 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);
-- 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);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
-- Find from the memory map the memory slots whose address intersects
-- the region [From .. To] and 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;
Into : in out MAT.Memory.Allocation_Map);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Reader : MAT.Readers.Reader_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
Declare the protected operation Find
|
Declare the protected operation Find
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b1041546858e8a4b68d6d6c5ad83a22ea9784364
|
src/orka/interface/orka-jobs-system.ads
|
src/orka/interface/orka-jobs-system.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 System.Multiprocessors;
with Orka.Jobs.Executors;
with Orka.Jobs.Queues;
with Orka.Jobs.Workers;
generic
Maximum_Queued_Jobs : Positive;
-- Maximum number of jobs that can be enqueued
--
-- Should be less than the largest width (number of jobs at a
-- particular level) of any job graph.
Maximum_Job_Graphs : Positive;
-- Maximum number of separate job graphs
--
-- For each job graph, a Future object is acquired. The number of
-- concurrent acquired objects is bounded by this number.
Maximum_Enqueued_By_Job : Positive;
-- Maximum number of extra jobs that a job can enqueue
package Orka.Jobs.System is
package Queues is new Jobs.Queues
(Maximum_Graphs => Maximum_Job_Graphs,
Capacity => Maximum_Queued_Jobs);
package Executors is new Jobs.Executors (Queues, Maximum_Enqueued_By_Job);
Queue : aliased Queues.Queue;
Number_Of_Workers : constant Standard.System.Multiprocessors.CPU;
procedure Shutdown;
private
package SM renames Standard.System.Multiprocessors;
use type SM.CPU;
Number_Of_Workers : constant SM.CPU := SM.Number_Of_CPUs - 1;
-- For n logical CPU's we spawn n - 1 workers (1 CPU is dedicated
-- to rendering)
package Workers is new Jobs.Workers
(Executors, Queue'Access, "Worker", Number_Of_Workers);
procedure Shutdown renames Workers.Shutdown;
end Orka.Jobs.System;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System.Multiprocessors;
with Orka.Jobs.Executors;
with Orka.Jobs.Queues;
with Orka.Jobs.Workers;
generic
Maximum_Queued_Jobs : Positive;
-- Maximum number of jobs that can be enqueued
--
-- Should be no less than the largest width (number of jobs at a
-- particular level) of any job graph.
Maximum_Job_Graphs : Positive;
-- Maximum number of separate job graphs
--
-- For each job graph, a Future object is acquired. The number of
-- concurrent acquired objects is bounded by this number.
package Orka.Jobs.System is
package Queues is new Jobs.Queues
(Maximum_Graphs => Maximum_Job_Graphs,
Capacity => Maximum_Queued_Jobs);
package Executors is new Jobs.Executors
(Queues, Maximum_Enqueued_By_Job => Maximum_Queued_Jobs);
Queue : aliased Queues.Queue;
Number_Of_Workers : constant Standard.System.Multiprocessors.CPU;
procedure Shutdown;
private
package SM renames Standard.System.Multiprocessors;
use type SM.CPU;
Number_Of_Workers : constant SM.CPU := SM.Number_Of_CPUs - 1;
-- For n logical CPU's we spawn n - 1 workers (1 CPU is dedicated
-- to rendering)
package Workers is new Jobs.Workers
(Executors, Queue'Access, "Worker", Number_Of_Workers);
procedure Shutdown renames Workers.Shutdown;
end Orka.Jobs.System;
|
Remove generic parameter from Orka.Jobs.System
|
orka: Remove generic parameter from Orka.Jobs.System
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
63b2f9f0698ecdf7f131b70a1410d005dd8714c0
|
examples/src/orka_10_compute.adb
|
examples/src/orka_10_compute.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 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.Real_Time;
with Ada.Text_IO;
with GL.Barriers;
with GL.Compute;
with GL.Types.Compute;
with Orka.Contexts.AWT;
with Orka.Debug;
with Orka.Rendering.Buffers;
with Orka.Rendering.Programs.Modules;
with Orka.Rendering.Programs.Uniforms;
with Orka.Resources.Locations.Directories;
with Orka.Types;
procedure Orka_10_Compute is
Context : constant Orka.Contexts.Context'Class := Orka.Contexts.AWT.Create_Context
(Version => (4, 2), Flags => (Debug => True, others => False));
----------------------------------------------------------------------
use Ada.Text_IO;
use type GL.Types.Int;
use GL.Types;
Numbers : constant Int_Array
:= (10, 1, 8, -1, 0, -2, 3, 5, -2, -3, 2, 7, 0, 11, 0, 2);
begin
Orka.Debug.Set_Log_Messages (Enable => True);
declare
use Orka.Rendering.Buffers;
use Orka.Rendering.Programs;
use Orka.Resources;
Location_Shaders : constant Locations.Location_Ptr
:= Locations.Directories.Create_Location ("data/shaders");
Program_1 : Program := Create_Program (Modules.Create_Module
(Location_Shaders, CS => "test-10-module-1.comp"));
Uniform_1 : constant Uniforms.Uniform := Program_1.Uniform ("maxNumbers");
Max_Work_Groups, Local_Size : Size;
begin
Program_1.Use_Program;
-- Print some limits about compute shaders
Put_Line ("Maximum shared size:" &
Size'Image (GL.Compute.Max_Compute_Shared_Memory_Size));
Put_Line ("Maximum invocations:" &
Size'Image (GL.Compute.Max_Compute_Work_Group_Invocations));
declare
R : GL.Types.Compute.Dimension_Size_Array;
use all type Orka.Index_Homogeneous;
begin
R := GL.Compute.Max_Compute_Work_Group_Count;
Put_Line ("Maximum count:" & R (X)'Image & R (Y)'Image & R (Z)'Image);
Max_Work_Groups := R (X);
R := GL.Compute.Max_Compute_Work_Group_Size;
Put_Line ("Maximum size: " & R (X)'Image & R (Y)'Image & R (Z)'Image);
R := Program_1.Compute_Work_Group_Size;
Put_Line ("Local size: " & R (X)'Image & R (Y)'Image & R (Z)'Image);
Local_Size := R (X);
end;
declare
use all type Orka.Types.Element_Type;
use type Ada.Real_Time.Time;
Factor : constant Size := (Max_Work_Groups * Local_Size) / Numbers'Length;
Buffer_1 : constant Buffer := Create_Buffer
(Flags => (Dynamic_Storage => True, others => False),
Kind => Int_Type,
Length => Numbers'Length * Natural (Factor));
A, B : Ada.Real_Time.Time;
procedure Memory_Barrier is
begin
GL.Barriers.Memory_Barrier ((Shader_Storage | Buffer_Update => True, others => False));
end Memory_Barrier;
begin
Put_Line ("Factor:" & Factor'Image);
-- Upload numbers to SSBO
for Index in 0 .. Factor - 1 loop
Buffer_1.Set_Data (Data => Numbers, Offset => Numbers'Length * Natural (Index));
end loop;
Buffer_1.Bind (Shader_Storage, 0);
A := Ada.Real_Time.Clock;
declare
Count : constant Size := Size (Buffer_1.Length);
Ceiling : Size := Count + (Count rem Local_Size);
Groups : Size := Ceiling / Local_Size;
begin
Put_Line ("Numbers:" & Count'Image);
Put_Line ("Groups: " & Groups'Image);
pragma Assert (Groups <= Max_Work_Groups);
-- The uniform is used to set how many numbers need to be
-- summed. If a work group has more threads than there are
-- numbers to be summed (happens in the last iteration),
-- then these threads will use the number 0 in the shader.
Uniform_1.Set_UInt (UInt (Count));
while Groups > 0 loop
-- Add an SSBO barrier for the next iteration
-- and then dispatch the compute shader
Memory_Barrier;
GL.Compute.Dispatch_Compute (X => UInt (Groups));
Uniform_1.Set_UInt (UInt (Groups));
Ceiling := Groups + (Groups rem Local_Size);
Groups := Ceiling / Local_Size;
end loop;
-- Perform last iteration. Work groups in X dimension needs
-- to be at least one.
Memory_Barrier;
GL.Compute.Dispatch_Compute (X => UInt (Size'Max (1, Groups)));
end;
Memory_Barrier;
declare
Output : Int_Array (1 .. 2) := (others => 0);
begin
Buffer_1.Get_Data (Output);
Put_Line ("Expected Sum:" & Size'Image (Factor * 41));
Put_Line ("Computed sum:" & Output (Output'First)'Image);
-- Print the number of shader invocations that execute in
-- lockstep. This requires the extension ARB_shader_ballot
-- in the shader.
Put_Line ("Sub-group size:" & Output (Output'Last)'Image);
end;
B := Ada.Real_Time.Clock;
Put_Line (Duration'Image (1e3 * Ada.Real_Time.To_Duration (B - A)) & " ms");
end;
end;
end Orka_10_Compute;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 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.Real_Time;
with Ada.Text_IO;
with GL.Barriers;
with GL.Compute;
with GL.Types.Compute;
with Orka.Contexts.AWT;
with Orka.Debug;
with Orka.Rendering.Buffers;
with Orka.Rendering.Programs.Modules;
with Orka.Rendering.Programs.Uniforms;
with Orka.Resources.Locations.Directories;
with Orka.Types;
procedure Orka_10_Compute is
Context : constant Orka.Contexts.Context'Class := Orka.Contexts.AWT.Create_Context
(Version => (4, 2), Flags => (Debug => True, others => False));
----------------------------------------------------------------------
use Ada.Text_IO;
use type GL.Types.Int;
use GL.Types;
Numbers : constant Int_Array
:= (10, 1, 8, -1, 0, -2, 3, 5, -2, -3, 2, 7, 0, 11, 0, 2);
begin
Orka.Debug.Set_Log_Messages (Enable => True);
declare
use Orka.Rendering.Buffers;
use Orka.Rendering.Programs;
use Orka.Resources;
Location_Shaders : constant Locations.Location_Ptr
:= Locations.Directories.Create_Location ("data/shaders");
Program_1 : Program := Create_Program (Modules.Create_Module
(Location_Shaders, CS => "test-10-module-1.comp"));
Uniform_1 : constant Uniforms.Uniform := Program_1.Uniform ("maxNumbers");
Max_Work_Groups, Local_Size : Size;
begin
Program_1.Use_Program;
-- Print some limits about compute shaders
Put_Line ("Maximum shared size:" &
Size'Image (GL.Compute.Max_Compute_Shared_Memory_Size));
Put_Line ("Maximum invocations:" &
Size'Image (GL.Compute.Max_Compute_Work_Group_Invocations));
declare
R : GL.Types.Compute.Dimension_Size_Array;
use all type Orka.Index_4D;
begin
R := GL.Compute.Max_Compute_Work_Group_Count;
Put_Line ("Maximum count:" & R (X)'Image & R (Y)'Image & R (Z)'Image);
Max_Work_Groups := R (X);
R := GL.Compute.Max_Compute_Work_Group_Size;
Put_Line ("Maximum size: " & R (X)'Image & R (Y)'Image & R (Z)'Image);
R := Program_1.Compute_Work_Group_Size;
Put_Line ("Local size: " & R (X)'Image & R (Y)'Image & R (Z)'Image);
Local_Size := R (X);
end;
declare
use all type Orka.Types.Element_Type;
use type Ada.Real_Time.Time;
Factor : constant Size := (Max_Work_Groups * Local_Size) / Numbers'Length;
Buffer_1 : constant Buffer := Create_Buffer
(Flags => (Dynamic_Storage => True, others => False),
Kind => Int_Type,
Length => Numbers'Length * Natural (Factor));
A, B : Ada.Real_Time.Time;
procedure Memory_Barrier is
begin
GL.Barriers.Memory_Barrier ((Shader_Storage | Buffer_Update => True, others => False));
end Memory_Barrier;
begin
Put_Line ("Factor:" & Factor'Image);
-- Upload numbers to SSBO
for Index in 0 .. Factor - 1 loop
Buffer_1.Set_Data (Data => Numbers, Offset => Numbers'Length * Natural (Index));
end loop;
Buffer_1.Bind (Shader_Storage, 0);
A := Ada.Real_Time.Clock;
declare
Count : constant Size := Size (Buffer_1.Length);
Ceiling : Size := Count + (Count rem Local_Size);
Groups : Size := Ceiling / Local_Size;
begin
Put_Line ("Numbers:" & Count'Image);
Put_Line ("Groups: " & Groups'Image);
pragma Assert (Groups <= Max_Work_Groups);
-- The uniform is used to set how many numbers need to be
-- summed. If a work group has more threads than there are
-- numbers to be summed (happens in the last iteration),
-- then these threads will use the number 0 in the shader.
Uniform_1.Set_UInt (UInt (Count));
while Groups > 0 loop
-- Add an SSBO barrier for the next iteration
-- and then dispatch the compute shader
Memory_Barrier;
GL.Compute.Dispatch_Compute (X => UInt (Groups));
Uniform_1.Set_UInt (UInt (Groups));
Ceiling := Groups + (Groups rem Local_Size);
Groups := Ceiling / Local_Size;
end loop;
-- Perform last iteration. Work groups in X dimension needs
-- to be at least one.
Memory_Barrier;
GL.Compute.Dispatch_Compute (X => UInt (Size'Max (1, Groups)));
end;
Memory_Barrier;
declare
Output : Int_Array (1 .. 2) := (others => 0);
begin
Buffer_1.Get_Data (Output);
Put_Line ("Expected Sum:" & Size'Image (Factor * 41));
Put_Line ("Computed sum:" & Output (Output'First)'Image);
-- Print the number of shader invocations that execute in
-- lockstep. This requires the extension ARB_shader_ballot
-- in the shader.
Put_Line ("Sub-group size:" & Output (Output'Last)'Image);
end;
B := Ada.Real_Time.Clock;
Put_Line (Duration'Image (1e3 * Ada.Real_Time.To_Duration (B - A)) & " ms");
end;
end;
end Orka_10_Compute;
|
Rename occurrences of Index_Homogeneous to Index_4D
|
examples: Rename occurrences of Index_Homogeneous to Index_4D
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
9fa6d05cfea4605dfd3c195d742a67e9f494ef2c
|
awa/plugins/awa-images/src/awa-images-services.adb
|
awa/plugins/awa-images/src/awa-images-services.adb
|
-----------------------------------------------------------------------
-- awa-images-services -- Image service
-- Copyright (C) 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.Processes;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Streams.Pipes;
with Util.Streams.Texts;
with ADO;
with ADO.Sessions;
with AWA.Images.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
with AWA.Storages.Modules;
with Ada.Strings.Unbounded;
with EL.Variables.Default;
with EL.Contexts.Default;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
package body AWA.Images.Services is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Image Service
-- ------------------------------
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services");
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Image_Service;
Module : in AWA.Modules.Module'Class) is
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND);
end Initialize;
procedure Create_Thumbnail (Service : in Image_Service;
Source : in String;
Into : in String;
Width : out Natural;
Height : out Natural) is
Ctx : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
Proc : Util.Processes.Process;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
begin
Variables.Bind ("src", Util.Beans.Objects.To_Object (Source));
Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into));
Ctx.Set_Variable_Mapper (Variables'Unchecked_Access);
declare
Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx);
Command : constant String := Util.Beans.Objects.To_String (Cmd);
Input : Util.Streams.Texts.Reader_Stream;
begin
Width := 0;
Height := 0;
Pipe.Open (Command, Util.Processes.READ_ALL);
Input.Initialize (null, Pipe'Unchecked_Access, 1024);
while not Input.Is_Eof loop
declare
use Ada.Strings;
Line : Ada.Strings.Unbounded.Unbounded_String;
Pos : Natural;
Sep : Natural;
Last : Natural;
begin
Input.Read_Line (Into => Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Info ("Received: {0}", Line);
-- The '-verbose' option of ImageMagick reports information about the original
-- image. Extract the picture width and height.
-- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018
Pos := Ada.Strings.Unbounded.Index (Line, " ");
if Pos > 0 and Width = 0 then
Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1);
if Pos > 0 then
Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1);
Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1);
if Sep > 0 and Sep < Last then
Log.Info ("Dimension {0} - {1}..{2}",
Ada.Strings.Unbounded.Slice (Line, Pos, Last),
Natural'Image (Pos), Natural'Image (Last));
Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1));
Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1));
end if;
end if;
end if;
end;
end loop;
Pipe.Close;
Util.Processes.Wait (Proc);
if Pipe.Get_Exit_Status /= 0 then
Log.Error ("Command {0} exited with status {1}", Command,
Integer'Image (Pipe.Get_Exit_Status));
end if;
end;
end Create_Thumbnail;
-- Build a thumbnail for the image identified by the Id.
procedure Build_Thumbnail (Service : in Image_Service;
Id : in ADO.Identifier) is
Storage_Service : constant AWA.Storages.Services.Storage_Service_Access
:= AWA.Storages.Modules.Get_Storage_Manager;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
Thumb : AWA.Images.Models.Image_Ref;
Target_File : AWA.Storages.Storage_File;
Local_File : AWA.Storages.Storage_File;
Thumbnail : AWA.Storages.Models.Storage_Ref;
Width : Natural;
Height : Natural;
Name : Ada.Strings.Unbounded.Unbounded_String;
begin
Img.Load (DB, Id);
declare
Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage;
begin
Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File);
Storage_Service.Create_Local_File (Target_File);
Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File),
AWA.Storages.Get_Path (Target_File), Width, Height);
Thumbnail.Set_Mime_Type ("image/jpeg");
Thumbnail.Set_Original (Image_File);
Thumbnail.Set_Workspace (Image_File.Get_Workspace);
Thumbnail.Set_Folder (Image_File.Get_Folder);
Thumbnail.Set_Owner (Image_File.Get_Owner);
Thumbnail.Set_Name (String '(Image_File.Get_Name));
Storage_Service.Save (Thumbnail, Target_File, AWA.Storages.Models.DATABASE);
Thumb.Set_Width (64);
Thumb.Set_Height (64);
Thumb.Set_Owner (Image_File.Get_Owner);
Thumb.Set_Folder (Image_File.Get_Folder);
Thumb.Set_Storage (Thumbnail);
Img.Set_Width (Width);
Img.Set_Height (Height);
Img.Set_Thumb_Width (64);
Img.Set_Thumb_Height (64);
Img.Set_Thumbnail (Thumbnail);
Ctx.Start;
Img.Save (DB);
Thumb.Save (DB);
Ctx.Commit;
end;
end Build_Thumbnail;
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Create_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
begin
Ctx.Start;
Img.Set_Width (0);
Img.Set_Height (0);
Img.Set_Thumb_Height (0);
Img.Set_Thumb_Width (0);
Img.Set_Storage (File);
Img.Set_Folder (File.Get_Folder);
Img.Set_Owner (File.Get_Owner);
Img.Save (DB);
Ctx.Commit;
end Create_Image;
-- Deletes the storage instance.
procedure Delete_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
begin
null;
end Delete_Image;
end AWA.Images.Services;
|
-----------------------------------------------------------------------
-- awa-images-services -- Image service
-- Copyright (C) 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.Processes;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Util.Streams.Pipes;
with Util.Streams.Texts;
with Util.Strings;
with ADO;
with ADO.Sessions;
with AWA.Images.Models;
with AWA.Services.Contexts;
with AWA.Storages.Services;
with AWA.Storages.Modules;
with Ada.Strings.Unbounded;
with EL.Variables.Default;
with EL.Contexts.Default;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
package body AWA.Images.Services is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Image Service
-- ------------------------------
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services");
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Image_Service;
Module : in AWA.Modules.Module'Class) is
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Thumbnail_Command := Module.Get_Config (PARAM_THUMBNAIL_COMMAND);
end Initialize;
procedure Create_Thumbnail (Service : in Image_Service;
Source : in String;
Into : in String;
Width : in out Natural;
Height : in out Natural) is
Ctx : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
Proc : Util.Processes.Process;
Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
begin
Variables.Bind ("src", Util.Beans.Objects.To_Object (Source));
Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into));
Variables.Bind ("width", Util.Beans.Objects.To_Object (Width));
Variables.Bind ("height", Util.Beans.Objects.To_Object (Height));
Ctx.Set_Variable_Mapper (Variables'Unchecked_Access);
declare
Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx);
Command : constant String := Util.Beans.Objects.To_String (Cmd);
Input : Util.Streams.Texts.Reader_Stream;
begin
Width := 0;
Height := 0;
Pipe.Open (Command, Util.Processes.READ_ALL);
Input.Initialize (null, Pipe'Unchecked_Access, 1024);
while not Input.Is_Eof loop
declare
use Ada.Strings;
Line : Ada.Strings.Unbounded.Unbounded_String;
Pos : Natural;
Sep : Natural;
Last : Natural;
begin
Input.Read_Line (Into => Line, Strip => False);
exit when Ada.Strings.Unbounded.Length (Line) = 0;
Log.Info ("Received: {0}", Line);
-- The '-verbose' option of ImageMagick reports information about the original
-- image. Extract the picture width and height.
-- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018
Pos := Ada.Strings.Unbounded.Index (Line, " ");
if Pos > 0 and Width = 0 then
Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1);
if Pos > 0 then
Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1);
Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1);
if Sep > 0 and Sep < Last then
Log.Info ("Dimension {0} - {1}..{2}",
Ada.Strings.Unbounded.Slice (Line, Pos, Last),
Natural'Image (Pos), Natural'Image (Last));
Width := Natural'Value (Unbounded.Slice (Line, Pos + 1, Sep - 1));
Height := Natural'Value (Unbounded.Slice (Line, Sep + 1, Last - 1));
end if;
end if;
end if;
end;
end loop;
Pipe.Close;
Util.Processes.Wait (Proc);
if Pipe.Get_Exit_Status /= 0 then
Log.Error ("Command {0} exited with status {1}", Command,
Integer'Image (Pipe.Get_Exit_Status));
end if;
end;
end Create_Thumbnail;
-- Build a thumbnail for the image identified by the Id.
procedure Build_Thumbnail (Service : in Image_Service;
Id : in ADO.Identifier) is
Storage_Service : constant AWA.Storages.Services.Storage_Service_Access
:= AWA.Storages.Modules.Get_Storage_Manager;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
Thumb : AWA.Images.Models.Image_Ref;
Target_File : AWA.Storages.Storage_File (AWA.Storages.TMP);
Local_File : AWA.Storages.Storage_File (AWA.Storages.CACHE);
Thumbnail : AWA.Storages.Models.Storage_Ref;
Width : Natural := 64;
Height : Natural := 64;
Name : Ada.Strings.Unbounded.Unbounded_String;
begin
Img.Load (DB, Id);
declare
Image_File : constant AWA.Storages.Models.Storage_Ref'Class := Img.Get_Storage;
begin
Storage_Service.Get_Local_File (From => Image_File.Get_Id, Into => Local_File);
Storage_Service.Create_Local_File (Target_File);
Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File),
AWA.Storages.Get_Path (Target_File), Width, Height);
Thumbnail.Set_Mime_Type ("image/jpeg");
Thumbnail.Set_Original (Image_File);
Thumbnail.Set_Workspace (Image_File.Get_Workspace);
Thumbnail.Set_Folder (Image_File.Get_Folder);
Thumbnail.Set_Owner (Image_File.Get_Owner);
Thumbnail.Set_Name (String '(Image_File.Get_Name));
Storage_Service.Save (Thumbnail, AWA.Storages.Get_Path (Target_File),
AWA.Storages.Models.DATABASE);
Thumb.Set_Width (64);
Thumb.Set_Height (64);
Thumb.Set_Owner (Image_File.Get_Owner);
Thumb.Set_Folder (Image_File.Get_Folder);
Thumb.Set_Storage (Thumbnail);
Img.Set_Width (Width);
Img.Set_Height (Height);
Img.Set_Thumb_Width (64);
Img.Set_Thumb_Height (64);
Img.Set_Thumbnail (Thumbnail);
Ctx.Start;
Img.Save (DB);
Thumb.Save (DB);
Ctx.Commit;
end;
end Build_Thumbnail;
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Create_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Img : AWA.Images.Models.Image_Ref;
begin
Ctx.Start;
Img.Set_Width (0);
Img.Set_Height (0);
Img.Set_Thumb_Height (0);
Img.Set_Thumb_Width (0);
Img.Set_Storage (File);
Img.Set_Folder (File.Get_Folder);
Img.Set_Owner (File.Get_Owner);
Img.Save (DB);
Ctx.Commit;
end Create_Image;
-- Deletes the storage instance.
procedure Delete_Image (Service : in Image_Service;
File : in AWA.Storages.Models.Storage_Ref'Class) is
begin
null;
end Delete_Image;
-- ------------------------------
-- Scale the image dimension.
-- ------------------------------
procedure Scale (Width : in Natural;
Height : in Natural;
To_Width : in out Natural;
To_Height : in out Natural) is
begin
if To_Width = Natural'Last or To_Height = Natural'Last
or (To_Width = 0 and To_Height = 0)
then
To_Width := Width;
To_Height := Height;
elsif To_Width = 0 then
To_Width := (Width * To_Height) / Height;
elsif To_Height = 0 then
To_Height := (Height * To_Width) / Width;
end if;
end Scale;
-- ------------------------------
-- Get the dimension represented by the string. The string has one of the following
-- formats:
-- original -> Width, Height := Natural'Last
-- default -> Width, Height := 0
-- <width>x -> Width := <width>, Height := 0
-- x<height> -> Width := 0, Height := <height>
-- <width>x<height> -> Width := <width>, Height := <height>
-- ------------------------------
procedure Get_Sizes (Dimension : in String;
Width : out Natural;
Height : out Natural) is
Pos : Natural;
begin
if Dimension = "original" then
Width := Natural'Last;
Height := Natural'Last;
elsif Dimension = "default" then
Width := 800;
Height := 0;
else
Pos := Util.Strings.Index (Dimension, 'x');
if Pos > Dimension'First then
Width := Natural'Value (Dimension (Dimension'First .. Pos - 1));
else
Width := 0;
end if;
if Pos < Dimension'Last then
Height := Natural'Value (Dimension (Pos + 1 .. Dimension'Last));
else
Height := 0;
end if;
end if;
end Get_Sizes;
end AWA.Images.Services;
|
Implement the Get_Size and Scale operation Update the thumbnail operation to allow scaling to any target width/height
|
Implement the Get_Size and Scale operation
Update the thumbnail operation to allow scaling to any target width/height
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b3e41c0fdad1db576a70f72e656d094bccba9d88
|
awa/src/awa-helpers-requests.adb
|
awa/src/awa-helpers-requests.adb
|
-----------------------------------------------------------------------
-- awa-helpers-requests -- Helpers for AWA applications
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Dates.ISO8601;
with ASF.Contexts.Faces;
package body AWA.Helpers.Requests is
-- ------------------------------
-- Get the parameter identified by the given name and return it as an identifier.
-- Returns NO_IDENTIFIER if the parameter does not exist or is not valid.
-- ------------------------------
function Get_Parameter (Name : in String) return ADO.Identifier is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier'Value (P);
end if;
exception
when others =>
return ADO.NO_IDENTIFIER;
end Get_Parameter;
-- ------------------------------
-- Get the parameter identified by the given name and return it as an integer.
-- Returns the default value if the parameter does not exist or is not valid.
-- ------------------------------
function Get_Parameter (Name : in String;
Default : in Integer) return Integer is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return Default;
else
return Integer'Value (P);
end if;
exception
when others =>
return Default;
end Get_Parameter;
-- ------------------------------
-- Get the parameter identified by the given name and return it as a string.
-- Returns the default value if the parameter does not exist or is not valid.
-- ------------------------------
function Get_Parameter (Name : in String;
Default : in String) return String is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return Default;
else
return P;
end if;
exception
when others =>
return Default;
end Get_Parameter;
-- ------------------------------
-- Get the parameter identified by the given name and return it as a date.
-- Returns the default value if the parameter does not exist or is not a valid date.
-- The date is assumed to be in ISO8601 format.
-- ------------------------------
function Get_Parameter (Name : in String;
Default : in String) return Ada.Calendar.Time is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return Util.Dates.ISO8601.Value (Default);
else
return Util.Dates.ISO8601.Value (P);
end if;
exception
when others =>
return Util.Dates.ISO8601.Value (Default);
end Get_Parameter;
end AWA.Helpers.Requests;
|
-----------------------------------------------------------------------
-- awa-helpers-requests -- Helpers for AWA applications
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Dates.ISO8601;
with ASF.Contexts.Faces;
package body AWA.Helpers.Requests is
-- ------------------------------
-- Get the parameter identified by the given name and return it as an identifier.
-- Returns NO_IDENTIFIER if the parameter does not exist or is not valid.
-- ------------------------------
function Get_Parameter (Name : in String) return ADO.Identifier is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier'Value (P);
end if;
exception
when others =>
return ADO.NO_IDENTIFIER;
end Get_Parameter;
-- ------------------------------
-- Get the parameter identified by the given name and return it as an integer.
-- Returns the default value if the parameter does not exist or is not valid.
-- ------------------------------
function Get_Parameter (Name : in String;
Default : in Integer) return Integer is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return Default;
else
return Integer'Value (P);
end if;
exception
when others =>
return Default;
end Get_Parameter;
-- ------------------------------
-- Get the parameter identified by the given name and return it as a string.
-- Returns the default value if the parameter does not exist or is not valid.
-- ------------------------------
function Get_Parameter (Name : in String;
Default : in String) return String is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return Default;
else
return P;
end if;
exception
when others =>
return Default;
end Get_Parameter;
-- ------------------------------
-- Get the parameter identified by the given name and return it as a date.
-- Returns the default value if the parameter does not exist or is not a valid date.
-- The date is assumed to be in ISO8601 format.
-- ------------------------------
function Get_Parameter (Name : in String;
Default : in String) return Ada.Calendar.Time is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
if P = "" then
return Util.Dates.ISO8601.Value (Default);
else
return Util.Dates.ISO8601.Value (P);
end if;
exception
when others =>
return Util.Dates.ISO8601.Value (Default);
end Get_Parameter;
-- ------------------------------
-- Get the parameter identified by the given name and return it as an Object.
-- Returns the NULL object value if the parameter does not exist.
-- ------------------------------
function Get_Parameter (Name : in String) return Util.Beans.Objects.Object is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
P : constant String := Ctx.Get_Parameter (Name);
begin
return Util.Beans.Objects.To_Object (P);
exception
when others =>
return Util.Beans.Objects.Null_Object;
end Get_Parameter;
end AWA.Helpers.Requests;
|
Implement the new Get_Parameter operation
|
Implement the new Get_Parameter operation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
af85e7e09c613824d58d4657c91dff9e2f77c93b
|
src/sqlite/ado-statements-sqlite.ads
|
src/sqlite/ado-statements-sqlite.ads
|
-----------------------------------------------------------------------
-- ado-statements-sqlite -- SQLite database statements
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sqlite3_H;
with ADO.Drivers.Connections.Sqlite;
package ADO.Statements.Sqlite is
type Handle is null record;
-- ------------------------------
-- Delete statement
-- ------------------------------
type Sqlite_Delete_Statement is new Delete_Statement with private;
type Sqlite_Delete_Statement_Access is access all Sqlite_Delete_Statement'Class;
-- Execute the query
overriding
procedure Execute (Stmt : in out Sqlite_Delete_Statement;
Result : out Natural);
-- Create the delete statement
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access;
-- ------------------------------
-- Update statement
-- ------------------------------
type Sqlite_Update_Statement is new Update_Statement with private;
type Sqlite_Update_Statement_Access is access all Sqlite_Update_Statement'Class;
-- Execute the query
overriding
procedure Execute (Stmt : in out Sqlite_Update_Statement);
-- Execute the query
overriding
procedure Execute (Stmt : in out Sqlite_Update_Statement;
Result : out Integer);
-- Create an update statement
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access;
-- ------------------------------
-- Insert statement
-- ------------------------------
type Sqlite_Insert_Statement is new Insert_Statement with private;
type Sqlite_Insert_Statement_Access is access all Sqlite_Insert_Statement'Class;
-- Execute the query
overriding
procedure Execute (Stmt : in out Sqlite_Insert_Statement;
Result : out Integer);
-- Create an insert statement.
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access;
-- ------------------------------
-- Query statement for SQLite
-- ------------------------------
type Sqlite_Query_Statement is new Query_Statement with private;
type Sqlite_Query_Statement_Access is access all Sqlite_Query_Statement'Class;
-- Execute the query
overriding
procedure Execute (Query : in out Sqlite_Query_Statement);
-- Get the number of rows returned by the query
overriding
function Get_Row_Count (Query : in Sqlite_Query_Statement) return Natural;
-- Returns True if there is more data (row) to fetch
overriding
function Has_Elements (Query : in Sqlite_Query_Statement) return Boolean;
-- Fetch the next row
overriding
procedure Next (Query : in out Sqlite_Query_Statement);
-- Returns true if the column <b>Column</b> is null.
overriding
function Is_Null (Query : in Sqlite_Query_Statement;
Column : in Natural) return Boolean;
-- Get the column value at position <b>Column</b> and
-- return it as an <b>Int64</b>.
-- Raises <b>Invalid_Type</b> if the value cannot be converted.
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_Int64 (Query : Sqlite_Query_Statement;
Column : Natural) return Int64;
-- Get the column value at position <b>Column</b> and
-- return it as an <b>Unbounded_String</b>.
-- Raises <b>Invalid_Type</b> if the value cannot be converted.
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_Unbounded_String (Query : Sqlite_Query_Statement;
Column : Natural) return Unbounded_String;
-- Get the column value at position <b>Column</b> and
-- return it as an <b>Unbounded_String</b>.
-- Raises <b>Invalid_Type</b> if the value cannot be converted.
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_String (Query : Sqlite_Query_Statement;
Column : Natural) return String;
-- Get the column value at position <b>Column</b> and
-- return it as a <b>Blob</b> reference.
overriding
function Get_Blob (Query : in Sqlite_Query_Statement;
Column : in Natural) return ADO.Blob_Ref;
-- Get the column value at position <b>Column</b> and
-- return it as an <b>Time</b>.
-- Raises <b>Invalid_Type</b> if the value cannot be converted.
-- Raises <b>Invalid_Column</b> if the column does not exist.
function Get_Time (Query : Sqlite_Query_Statement;
Column : Natural) return Ada.Calendar.Time;
-- Get the column type
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_Column_Type (Query : Sqlite_Query_Statement;
Column : Natural)
return ADO.Schemas.Column_Type;
-- Get the column name.
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_Column_Name (Query : in Sqlite_Query_Statement;
Column : in Natural)
return String;
-- Get the number of columns in the result.
overriding
function Get_Column_Count (Query : in Sqlite_Query_Statement)
return Natural;
-- Deletes the query statement.
overriding
procedure Finalize (Query : in out Sqlite_Query_Statement);
-- Create the query statement.
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access;
-- Create the query statement.
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Query : in String)
return Query_Statement_Access;
-- Execute SQL statement.
procedure Execute (Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
SQL : in String);
private
type State is (HAS_ROW, HAS_MORE, DONE, ERROR);
type Sqlite_Query_Statement is new Query_Statement with record
This_Query : aliased ADO.SQL.Query;
Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Stmt : access Sqlite3_H.sqlite3_stmt;
Counter : Natural := 1;
Status : State := DONE;
Max_Column : Natural;
end record;
type Sqlite_Delete_Statement is new Delete_Statement with record
Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : ADO.Schemas.Class_Mapping_Access;
Delete_Query : aliased ADO.SQL.Query;
end record;
type Sqlite_Update_Statement is new Update_Statement with record
Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
This_Query : aliased ADO.SQL.Update_Query;
Table : ADO.Schemas.Class_Mapping_Access;
end record;
type Sqlite_Insert_Statement is new Insert_Statement with record
Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
This_Query : aliased ADO.SQL.Update_Query;
Table : ADO.Schemas.Class_Mapping_Access;
end record;
-- Check for an error after executing a sqlite statement.
procedure Check_Error (Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Result : in Interfaces.C.int);
end ADO.Statements.Sqlite;
|
-----------------------------------------------------------------------
-- ado-statements-sqlite -- SQLite database statements
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sqlite3_H;
with ADO.Drivers.Connections.Sqlite;
package ADO.Statements.Sqlite is
type Handle is null record;
-- ------------------------------
-- Delete statement
-- ------------------------------
type Sqlite_Delete_Statement is new Delete_Statement with private;
type Sqlite_Delete_Statement_Access is access all Sqlite_Delete_Statement'Class;
-- Execute the query
overriding
procedure Execute (Stmt : in out Sqlite_Delete_Statement;
Result : out Natural);
-- Create the delete statement
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access;
-- ------------------------------
-- Update statement
-- ------------------------------
type Sqlite_Update_Statement is new Update_Statement with private;
type Sqlite_Update_Statement_Access is access all Sqlite_Update_Statement'Class;
-- Execute the query
overriding
procedure Execute (Stmt : in out Sqlite_Update_Statement);
-- Execute the query
overriding
procedure Execute (Stmt : in out Sqlite_Update_Statement;
Result : out Integer);
-- Create an update statement
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access;
-- ------------------------------
-- Insert statement
-- ------------------------------
type Sqlite_Insert_Statement is new Insert_Statement with private;
type Sqlite_Insert_Statement_Access is access all Sqlite_Insert_Statement'Class;
-- Execute the query
overriding
procedure Execute (Stmt : in out Sqlite_Insert_Statement;
Result : out Integer);
-- Create an insert statement.
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access;
-- ------------------------------
-- Query statement for SQLite
-- ------------------------------
type Sqlite_Query_Statement is new Query_Statement with private;
type Sqlite_Query_Statement_Access is access all Sqlite_Query_Statement'Class;
-- Execute the query
overriding
procedure Execute (Query : in out Sqlite_Query_Statement);
-- Get the number of rows returned by the query
overriding
function Get_Row_Count (Query : in Sqlite_Query_Statement) return Natural;
-- Returns True if there is more data (row) to fetch
overriding
function Has_Elements (Query : in Sqlite_Query_Statement) return Boolean;
-- Fetch the next row
overriding
procedure Next (Query : in out Sqlite_Query_Statement);
-- Returns true if the column <b>Column</b> is null.
overriding
function Is_Null (Query : in Sqlite_Query_Statement;
Column : in Natural) return Boolean;
-- Get the column value at position <b>Column</b> and
-- return it as an <b>Int64</b>.
-- Raises <b>Invalid_Type</b> if the value cannot be converted.
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_Int64 (Query : Sqlite_Query_Statement;
Column : Natural) return Int64;
-- Get the column value at position <b>Column</b> and
-- return it as an <b>Unbounded_String</b>.
-- Raises <b>Invalid_Type</b> if the value cannot be converted.
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_Unbounded_String (Query : Sqlite_Query_Statement;
Column : Natural) return Unbounded_String;
-- Get the column value at position <b>Column</b> and
-- return it as an <b>Unbounded_String</b>.
-- Raises <b>Invalid_Type</b> if the value cannot be converted.
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_String (Query : Sqlite_Query_Statement;
Column : Natural) return String;
-- Get the column value at position <b>Column</b> and
-- return it as a <b>Blob</b> reference.
overriding
function Get_Blob (Query : in Sqlite_Query_Statement;
Column : in Natural) return ADO.Blob_Ref;
-- Get the column value at position <b>Column</b> and
-- return it as an <b>Time</b>.
-- Raises <b>Invalid_Type</b> if the value cannot be converted.
-- Raises <b>Invalid_Column</b> if the column does not exist.
function Get_Time (Query : Sqlite_Query_Statement;
Column : Natural) return Ada.Calendar.Time;
-- Get the column type
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_Column_Type (Query : Sqlite_Query_Statement;
Column : Natural)
return ADO.Schemas.Column_Type;
-- Get the column name.
-- Raises <b>Invalid_Column</b> if the column does not exist.
overriding
function Get_Column_Name (Query : in Sqlite_Query_Statement;
Column : in Natural)
return String;
-- Get the number of columns in the result.
overriding
function Get_Column_Count (Query : in Sqlite_Query_Statement)
return Natural;
-- Deletes the query statement.
overriding
procedure Finalize (Query : in out Sqlite_Query_Statement);
-- Create the query statement.
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access;
-- Create the query statement.
function Create_Statement (Database : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Query : in String)
return Query_Statement_Access;
-- Execute SQL statement.
procedure Execute (Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
SQL : in String);
private
type State is (HAS_ROW, HAS_MORE, DONE, ERROR);
type Sqlite_Query_Statement is new Query_Statement with record
This_Query : aliased ADO.SQL.Query;
Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Stmt : access Sqlite3_H.sqlite3_stmt;
Counter : Natural := 1;
Status : State := DONE;
Max_Column : Natural;
end record;
type Sqlite_Delete_Statement is new Delete_Statement with record
Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
Table : ADO.Schemas.Class_Mapping_Access;
Delete_Query : aliased ADO.SQL.Query;
end record;
type Sqlite_Update_Statement is new Update_Statement with record
Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
This_Query : aliased ADO.SQL.Update_Query;
Table : ADO.Schemas.Class_Mapping_Access;
end record;
type Sqlite_Insert_Statement is new Insert_Statement with record
Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
This_Query : aliased ADO.SQL.Update_Query;
Table : ADO.Schemas.Class_Mapping_Access;
end record;
-- Check for an error after executing a sqlite statement.
procedure Check_Error (Connection : access ADO.Drivers.Connections.Sqlite.Sqlite3;
SQL : in String;
Result : in Interfaces.C.int);
end ADO.Statements.Sqlite;
|
Add the SQL parameter to the Check_Error procedure
|
Add the SQL parameter to the Check_Error procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
42277670beddf154e180841e42a3e7681f380c67
|
asfunit/asf-server-tests.adb
|
asfunit/asf-server-tests.adb
|
-----------------------------------------------------------------------
-- asf.server -- ASF 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.
-----------------------------------------------------------------------
package body ASF.Server.Tests is
procedure Set_Context (Context : in ASF.Servlets.Servlet_Registry_Access) is
C : Request_Context;
begin
C.Application := Context;
C.Process := null;
ASF.Server.Set_Context (C);
end Set_Context;
end ASF.Server.Tests;
|
-----------------------------------------------------------------------
-- asf.server -- ASF 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.
-----------------------------------------------------------------------
package body ASF.Server.Tests is
procedure Set_Context (Context : in ASF.Servlets.Servlet_Registry_Access) is
C : Request_Context;
begin
C.Application := Context;
C.Request := null;
C.Response := null;
ASF.Server.Set_Context (C);
end Set_Context;
end ASF.Server.Tests;
|
Fix compilation of asfunit
|
Fix compilation of asfunit
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
bdc4b53e045a85fcefc7112c32f709799bf05ede
|
regtests/regtests.ads
|
regtests/regtests.ads
|
-----------------------------------------------------------------------
-- ADO Tests -- Database sequence generator
-- 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 ADO.Databases;
with ADO.Sessions;
package Regtests is
-- ------------------------------
-- Get the database manager to be used for the unit tests
-- ------------------------------
function Get_Controller return ADO.Databases.DataSource'Class;
-- ------------------------------
-- Get the readonly connection database to be used for the unit tests
-- ------------------------------
function Get_Database return ADO.Sessions.Session;
-- ------------------------------
-- Get the writeable connection database to be used for the unit tests
-- ------------------------------
function Get_Master_Database return ADO.Sessions.Master_Session;
-- ------------------------------
-- Initialize the test database
-- ------------------------------
procedure Initialize (Name : in String);
end Regtests;
|
-----------------------------------------------------------------------
-- ADO Tests -- Database sequence generator
-- Copyright (C) 2009, 2010, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Sessions;
with ADO.Sessions.Sources;
package Regtests is
-- ------------------------------
-- Get the database manager to be used for the unit tests
-- ------------------------------
function Get_Controller return ADO.Sessions.Sources.Data_Source'Class;
-- ------------------------------
-- Get the readonly connection database to be used for the unit tests
-- ------------------------------
function Get_Database return ADO.Sessions.Session;
-- ------------------------------
-- Get the writeable connection database to be used for the unit tests
-- ------------------------------
function Get_Master_Database return ADO.Sessions.Master_Session;
-- ------------------------------
-- Initialize the test database
-- ------------------------------
procedure Initialize (Name : in String);
end Regtests;
|
Update the unit test declaration
|
Update the unit test declaration
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
efdc3e8ea7156595fd9005565b6ca6e353188e60
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === 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 policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies. The framework defines a simple role based security policy and an URL security
-- policy intended to provide security in web applications. The security policy manager reads
-- some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components (yellow) are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance. Additional security policy context can be added depending on
-- the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === 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 policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies. The framework defines a simple role based security policy and an URL security
-- policy intended to provide security in web applications. The security policy manager reads
-- some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components (yellow) are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance. Additional security policy context can be added depending on
-- the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Make the OAuth and OpenID a separate wiki page
|
Make the OAuth and OpenID a separate wiki page
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
58555a90267160019af541cc6838d493af360ec2
|
components/touch_panel/ft6x06/stm32-touch_panel.adb
|
components/touch_panel/ft6x06/stm32-touch_panel.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 STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- Based on ft6x06.h from MCD Application Team
with Ada.Real_Time; use Ada.Real_Time;
with Ada.Unchecked_Conversion;
with STM32.Board; use STM32.Board;
with STM32.Device; use STM32.Device;
with STM32.I2C; use STM32.I2C;
with STM32.GPIO; use STM32.GPIO;
with STM32.LCD;
with FT6x06; use FT6x06;
package body STM32.Touch_Panel is
-- I2C Slave address of touchscreen FocalTech FT5336
TP_ADDR : constant := 16#54#;
procedure My_Delay (Ms : Integer);
-- Wait the specified number of milliseconds
function TP_Read (Reg : Byte; Status : out I2C_Status) return Byte
with Inline;
-- Reads a Touch Panel register value
procedure TP_Write (Reg : Byte; Data : Byte; Status : out I2C_Status)
with Inline;
-- Write a Touch Panel register value
procedure TP_Init_Pins;
-- Initializes the Touch Panel GPIO pins
procedure TP_I2C_Config;
-- Initializes the I2C bus
function Check_Id return Boolean;
-- Check the device Id: returns true on a FT5336 touch panel, False is
-- none is found.
procedure TP_Set_Use_Interrupts (Enabled : Boolean);
-- Whether the touch panel uses interrupts of polling to process touch
-- information
function Get_Touch_State
(Touch_Id : Byte;
Status : out I2C_Status) return TP_Touch_State;
-- Retrieves the position and pressure information of the specified
-- touch
pragma Warnings (Off, "* is not referenced");
pragma Warnings (On, "* is not referenced");
--------------
-- My_Delay --
--------------
procedure My_Delay (Ms : Integer) is
Next_Start : Time := Clock;
Period : constant Time_Span := Milliseconds (Ms);
begin
Next_Start := Next_Start + Period;
delay until Next_Start;
end My_Delay;
-------------
-- TS_Read --
-------------
function TP_Read (Reg : Byte; Status : out I2C_Status) return Byte
is
Ret : I2C_Data (1 .. 1);
begin
STM32.I2C.Mem_Read
(TP_I2C,
TP_ADDR,
Short (Reg),
Memory_Size_8b,
Ret,
Status,
1000);
return Ret (1);
end TP_Read;
-------------
-- TS_Read --
-------------
procedure TP_Write (Reg : Byte; Data : Byte; Status : out I2C_Status)
is
begin
STM32.I2C.Mem_Write
(TP_I2C,
TP_ADDR,
Short (Reg),
Memory_Size_8b,
(1 => Data),
Status,
1000);
end TP_Write;
---------------
-- Init_Pins --
---------------
procedure TP_Init_Pins
is
Pins : constant GPIO_Points := TP_Pins;
begin
Enable_Clock (Pins);
Reset (TP_I2C);
Configure_Alternate_Function (Pins, GPIO_AF_I2C);
Configure_IO (Pins,
(Speed => Speed_25MHz,
Mode => Mode_AF,
Output_Type => Open_Drain,
Resistors => Floating));
Lock (Pins);
Enable_Clock (TP_INT);
Configure_IO (TP_INT,
(Speed => Speed_50MHz,
Mode => Mode_In,
Output_Type => Open_Drain,
Resistors => Pull_Up));
Lock (TP_INT);
end TP_Init_Pins;
-------------------
-- TP_I2C_Config --
-------------------
procedure TP_I2C_Config
is
I2C_Conf : I2C_Configuration;
begin
-- Wait at least 200ms after power up before accessing the TP registers
My_Delay (200);
if not I2C.Port_Enabled (TP_I2C) then
Reset (TP_I2C);
I2C_Conf.Own_Address := 16#00#;
I2C_Conf.Addressing_Mode := Addressing_Mode_7bit;
I2C_Conf.General_Call_Enabled := False;
I2C_Conf.Clock_Stretching_Enabled := True;
I2C_Conf.Clock_Speed := 100_000;
Configure (TP_I2C, I2C_Conf);
end if;
end TP_I2C_Config;
---------------------------
-- TP_Set_Use_Interrupts --
---------------------------
procedure TP_Set_Use_Interrupts (Enabled : Boolean)
is
Reg_Value : Byte := 0;
Status : I2C_Status with Unreferenced;
begin
if Enabled then
Reg_Value := FT6206_G_MODE_INTERRUPT_TRIGGER;
else
Reg_Value := FT6206_G_MODE_INTERRUPT_POLLING;
end if;
TP_Write (FT6206_GMODE_REG, Reg_Value, Status);
end TP_Set_Use_Interrupts;
-------------
-- Read_Id --
-------------
function Check_Id return Boolean
is
Id : Byte;
Status : I2C_Status;
begin
for J in 1 .. 3 loop
Id := TP_Read (FT6206_CHIP_ID_REG, Status);
if Id = FT6206_ID_VALUE then
return True;
end if;
if Status = Err_Error then
return False;
end if;
end loop;
return False;
end Check_Id;
----------------
-- Initialize --
----------------
function Initialize return Boolean is
begin
TP_Init_Pins;
TP_I2C_Config;
TP_Set_Use_Interrupts (False);
return Check_Id;
end Initialize;
----------------
-- Initialize --
----------------
procedure Initialize is
Ret : Boolean with Unreferenced;
begin
Ret := Initialize;
end Initialize;
------------------
-- Detect_Touch --
------------------
function Detect_Touch return Natural
is
Status : I2C_Status;
Nb_Touch : Byte := 0;
begin
Nb_Touch := TP_Read (FT6206_TD_STAT_REG, Status);
if Status /= Ok then
return 0;
end if;
Nb_Touch := Nb_Touch and FT6206_TD_STAT_MASK;
if Nb_Touch > FT6206_Px_Regs'Last then
-- Overflow: set to 0
Nb_Touch := 0;
end if;
return Natural (Nb_Touch);
end Detect_Touch;
---------------------
-- Get_Touch_State --
---------------------
function Get_Touch_State
(Touch_Id : Byte;
Status : out I2C_Status) return TP_Touch_State
is
type Short_HL_Type is record
High, Low : Byte;
end record with Size => 16;
for Short_HL_Type use record
High at 1 range 0 .. 7;
Low at 0 range 0 .. 7;
end record;
function To_Short is
new Ada.Unchecked_Conversion (Short_HL_Type, Short);
RX : Natural;
RY : Natural;
Rtmp : Natural;
Ret : TP_Touch_State;
Regs : FT6206_Pressure_Registers;
Tmp : Short_HL_Type;
begin
if Touch_Id > 10 then
Status := Err_Error;
return (others => 0);
end if;
-- X/Y are swaped from the screen coordinates
Regs := FT6206_Px_Regs (Touch_Id);
Tmp.Low := TP_Read (Regs.XL_Reg, Status);
if Status /= Ok then
return Ret;
end if;
Tmp.High := TP_Read (Regs.XH_Reg, Status) and FT6206_TOUCH_POS_MSB_MASK;
if Status /= Ok then
return Ret;
end if;
RY := Natural (To_Short (Tmp) - 1);
Tmp.Low := TP_Read (Regs.YL_Reg, Status);
if Status /= Ok then
return Ret;
end if;
Tmp.High := TP_Read (Regs.YH_Reg, Status) and FT6206_TOUCH_POS_MSB_MASK;
if Status /= Ok then
return Ret;
end if;
RX := Natural (To_Short (Tmp) - 1);
Ret.Weight := Natural (TP_Read (Regs.Weight_Reg, Status));
if Status /= Ok then
Ret.Weight := 0;
return Ret;
end if;
if Ret.Weight = 0 then
Ret.Weight := 50;
end if;
if LCD.SwapXY then
RTmp := RX;
RX := RY;
RY := RTmp;
RX := STM32.LCD.Pixel_Width - RX - 1;
end if;
RX := Natural'Max (0, RX);
RY := Natural'Max (0, RY);
RX := Natural'Min (LCD.Pixel_Width - 1, RX);
RY := Natural'Min (LCD.Pixel_Height - 1, RY);
-- ??? On the STM32F426, Y is returned reverted
RY := STM32.LCD.LCD_Natural_Height - RY - 1;
Ret.X := RX;
Ret.Y := RY;
return Ret;
end Get_Touch_State;
---------------
-- Get_State --
---------------
function Get_State return TP_State
is
Status : I2C_Status;
N_Touch : constant Natural := Detect_Touch;
State : TP_State (1 .. N_Touch);
begin
if N_Touch = 0 then
return (1 .. 0 => <>);
end if;
for J in State'Range loop
State (J) := Get_Touch_State (Byte (J), Status);
if Status /= Ok then
return (1 .. 0 => <>);
end if;
end loop;
return State;
end Get_State;
end STM32.Touch_Panel;
|
------------------------------------------------------------------------------
-- --
-- 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 STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- Based on ft6x06.h from MCD Application Team
with Ada.Real_Time; use Ada.Real_Time;
with Ada.Unchecked_Conversion;
with STM32.Board; use STM32.Board;
with STM32.Device; use STM32.Device;
with STM32.I2C; use STM32.I2C;
with STM32.GPIO; use STM32.GPIO;
with STM32.LCD;
with FT6x06; use FT6x06;
package body STM32.Touch_Panel is
-- I2C Slave address of touchscreen FocalTech FT5336
TP_ADDR : constant := 16#54#;
procedure My_Delay (Ms : Integer);
-- Wait the specified number of milliseconds
function TP_Read (Reg : Byte; Status : out I2C_Status) return Byte
with Inline;
-- Reads a Touch Panel register value
procedure TP_Write (Reg : Byte; Data : Byte; Status : out I2C_Status)
with Inline;
-- Write a Touch Panel register value
procedure TP_Init_Pins;
-- Initializes the Touch Panel GPIO pins
procedure TP_I2C_Config;
-- Initializes the I2C bus
function Check_Id return Boolean;
-- Check the device Id: returns true on a FT5336 touch panel, False is
-- none is found.
procedure TP_Set_Use_Interrupts (Enabled : Boolean);
-- Whether the touch panel uses interrupts of polling to process touch
-- information
function Get_Touch_State
(Touch_Id : Byte;
Status : out I2C_Status) return TP_Touch_State;
-- Retrieves the position and pressure information of the specified
-- touch
pragma Warnings (Off, "* is not referenced");
pragma Warnings (On, "* is not referenced");
--------------
-- My_Delay --
--------------
procedure My_Delay (Ms : Integer) is
Next_Start : Time := Clock;
Period : constant Time_Span := Milliseconds (Ms);
begin
Next_Start := Next_Start + Period;
delay until Next_Start;
end My_Delay;
-------------
-- TS_Read --
-------------
function TP_Read (Reg : Byte; Status : out I2C_Status) return Byte
is
Ret : I2C_Data (1 .. 1);
begin
STM32.I2C.Mem_Read
(TP_I2C,
TP_ADDR,
Short (Reg),
Memory_Size_8b,
Ret,
Status,
1000);
return Ret (1);
end TP_Read;
-------------
-- TS_Read --
-------------
procedure TP_Write (Reg : Byte; Data : Byte; Status : out I2C_Status)
is
begin
STM32.I2C.Mem_Write
(TP_I2C,
TP_ADDR,
Short (Reg),
Memory_Size_8b,
(1 => Data),
Status,
1000);
end TP_Write;
---------------
-- Init_Pins --
---------------
procedure TP_Init_Pins
is
Pins : constant GPIO_Points := TP_Pins;
begin
Enable_Clock (Pins);
Reset (TP_I2C);
Configure_Alternate_Function (Pins, GPIO_AF_I2C);
Configure_IO (Pins,
(Speed => Speed_25MHz,
Mode => Mode_AF,
Output_Type => Open_Drain,
Resistors => Floating));
Lock (Pins);
Enable_Clock (TP_INT);
Configure_IO (TP_INT,
(Speed => Speed_50MHz,
Mode => Mode_In,
Output_Type => Open_Drain,
Resistors => Pull_Up));
Lock (TP_INT);
end TP_Init_Pins;
-------------------
-- TP_I2C_Config --
-------------------
procedure TP_I2C_Config
is
I2C_Conf : I2C_Configuration;
begin
-- Wait at least 200ms after power up before accessing the TP registers
My_Delay (200);
if not I2C.Port_Enabled (TP_I2C) then
Reset (TP_I2C);
I2C_Conf.Own_Address := 16#00#;
I2C_Conf.Addressing_Mode := Addressing_Mode_7bit;
I2C_Conf.General_Call_Enabled := False;
I2C_Conf.Clock_Stretching_Enabled := True;
I2C_Conf.Clock_Speed := 100_000;
Configure (TP_I2C, I2C_Conf);
end if;
end TP_I2C_Config;
---------------------------
-- TP_Set_Use_Interrupts --
---------------------------
procedure TP_Set_Use_Interrupts (Enabled : Boolean)
is
Reg_Value : Byte := 0;
Status : I2C_Status with Unreferenced;
begin
if Enabled then
Reg_Value := FT6206_G_MODE_INTERRUPT_TRIGGER;
else
Reg_Value := FT6206_G_MODE_INTERRUPT_POLLING;
end if;
TP_Write (FT6206_GMODE_REG, Reg_Value, Status);
end TP_Set_Use_Interrupts;
-------------
-- Read_Id --
-------------
function Check_Id return Boolean
is
Id : Byte;
Status : I2C_Status;
begin
for J in 1 .. 3 loop
Id := TP_Read (FT6206_CHIP_ID_REG, Status);
if Id = FT6206_ID_VALUE then
return True;
end if;
if Status = Err_Error then
return False;
end if;
end loop;
return False;
end Check_Id;
----------------
-- Initialize --
----------------
function Initialize return Boolean is
begin
TP_Init_Pins;
TP_I2C_Config;
TP_Set_Use_Interrupts (False);
return Check_Id;
end Initialize;
----------------
-- Initialize --
----------------
procedure Initialize is
Ret : Boolean with Unreferenced;
begin
Ret := Initialize;
end Initialize;
------------------
-- Detect_Touch --
------------------
function Detect_Touch return Natural
is
Status : I2C_Status;
Nb_Touch : Byte := 0;
begin
Nb_Touch := TP_Read (FT6206_TD_STAT_REG, Status);
if Status /= Ok then
return 0;
end if;
Nb_Touch := Nb_Touch and FT6206_TD_STAT_MASK;
if Nb_Touch > FT6206_Px_Regs'Last then
-- Overflow: set to 0
Nb_Touch := 0;
end if;
return Natural (Nb_Touch);
end Detect_Touch;
---------------------
-- Get_Touch_State --
---------------------
function Get_Touch_State
(Touch_Id : Byte;
Status : out I2C_Status) return TP_Touch_State
is
type Short_HL_Type is record
High, Low : Byte;
end record with Size => 16;
for Short_HL_Type use record
High at 1 range 0 .. 7;
Low at 0 range 0 .. 7;
end record;
function To_Short is
new Ada.Unchecked_Conversion (Short_HL_Type, Short);
RX : Natural;
RY : Natural;
Rtmp : Natural;
Ret : TP_Touch_State;
Regs : FT6206_Pressure_Registers;
Tmp : Short_HL_Type;
begin
if Touch_Id > 10 then
Status := Err_Error;
return (others => 0);
end if;
-- X/Y are swaped from the screen coordinates
Regs := FT6206_Px_Regs (Touch_Id);
Tmp.Low := TP_Read (Regs.XL_Reg, Status);
if Status /= Ok then
return Ret;
end if;
Tmp.High := TP_Read (Regs.XH_Reg, Status) and FT6206_TOUCH_POS_MSB_MASK;
if Status /= Ok then
return Ret;
end if;
RY := Natural (To_Short (Tmp) - 1);
Tmp.Low := TP_Read (Regs.YL_Reg, Status);
if Status /= Ok then
return Ret;
end if;
Tmp.High := TP_Read (Regs.YH_Reg, Status) and FT6206_TOUCH_POS_MSB_MASK;
if Status /= Ok then
return Ret;
end if;
RX := Natural (To_Short (Tmp) - 1);
Ret.Weight := Natural (TP_Read (Regs.Weight_Reg, Status));
if Status /= Ok then
Ret.Weight := 0;
return Ret;
end if;
if Ret.Weight = 0 then
Ret.Weight := 50;
end if;
if LCD.SwapXY then
RTmp := RX;
RX := RY;
RY := RTmp;
RX := STM32.LCD.Pixel_Width - RX - 1;
end if;
RX := Natural'Max (0, RX);
RY := Natural'Max (0, RY);
RX := Natural'Min (LCD.Pixel_Width - 1, RX);
RY := Natural'Min (LCD.Pixel_Height - 1, RY);
-- ??? On the STM32F426, Y is returned reverted
RY := STM32.LCD.LCD_Natural_Height - RY - 1;
RY := RY * 11 / 10;
Ret.X := RX;
Ret.Y := RY;
return Ret;
end Get_Touch_State;
---------------
-- Get_State --
---------------
function Get_State return TP_State
is
Status : I2C_Status;
N_Touch : constant Natural := Detect_Touch;
State : TP_State (1 .. N_Touch);
begin
if N_Touch = 0 then
return (1 .. 0 => <>);
end if;
for J in State'Range loop
State (J) := Get_Touch_State (Byte (J), Status);
if Status /= Ok then
return (1 .. 0 => <>);
end if;
end loop;
return State;
end Get_State;
end STM32.Touch_Panel;
|
Fix slight deviation between the touch panel coordinates and LCD coordinates.
|
Fix slight deviation between the touch panel coordinates and LCD coordinates.
On the STM32F469-disco board
|
Ada
|
bsd-3-clause
|
ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
|
19f83b0a5709ee2d9e53762e12faed92257a53c6
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
awa/plugins/awa-wikis/src/awa-wikis-modules.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Get;
with Util.Log.Loggers;
package body Awa.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
end Awa.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Modules.Get;
with AWA.Permissions;
with AWA.Permissions.Services;
with ADO.Sessions;
with Util.Log.Loggers;
package body AWA.Wikis.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Wikis.Module");
-- ------------------------------
-- Initialize the wikis module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the wikis module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the wikis module.
-- ------------------------------
function Get_Wiki_Module return Wiki_Module_Access is
function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);
begin
return Get;
end Get_Wiki_Module;
-- ------------------------------
-- Create the wiki space.
-- ------------------------------
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating new wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission,
Entity => WS);
Wiki.Set_Workspace (WS);
Wiki.Save (DB);
-- Add the permission for the user to use the new wiki space.
AWA.Permissions.Services.Add_Permission (Session => DB,
User => User,
Entity => Wiki);
Ctx.Commit;
Log.Info ("Wiki {0} created for user {1}",
ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User));
end Create_Wiki_Space;
-- ------------------------------
-- Save the wiki space.
-- ------------------------------
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Log.Info ("Updating wiki space {0}", String '(Wiki.Get_Name));
Ctx.Start;
-- Check that the user has the update permission on the given wiki space.
AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission,
Entity => Wiki);
Wiki.Save (DB);
Ctx.Commit;
end Save_Wiki_Space;
-- ------------------------------
-- Load the wiki space.
-- ------------------------------
procedure Load_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Module);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Wiki.Load (DB, Id, Found);
end Load_Wiki_Space;
end AWA.Wikis.Modules;
|
Implement the Create_Wiki_Space procedure
|
Implement the Create_Wiki_Space procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
7ab06506485525f247d473a7f4402f1ee81e2fa7
|
src/util-properties-discrete.ads
|
src/util-properties-discrete.ads
|
-----------------------------------------------------------------------
-- discrete properties -- Generic package for get/set of discrete properties
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
generic
type Property_Type is (<>);
-- with function To_String (Val : Property_Type) return String is <>;
-- with function From_String (Val : String) return Property_Type is <>;
package Util.Properties.Discrete is
-- Get the property value
function Get (Self : in Manager'Class;
Name : in String) return Property_Type;
-- Get the property value.
-- Return the default if the property does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in Property_Type) return Property_Type;
-- Set the property value
procedure Set (Self : in out Manager'Class;
Name : in String;
Value : in Property_Type);
end Util.Properties.Discrete;
|
-----------------------------------------------------------------------
-- util-properties-discrete -- Generic package for get/set of discrete properties
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
generic
type Property_Type is (<>);
-- with function To_String (Val : Property_Type) return String is <>;
-- with function From_String (Val : String) return Property_Type is <>;
package Util.Properties.Discrete is
-- Get the property value
function Get (Self : in Manager'Class;
Name : in String) return Property_Type;
-- Get the property value.
-- Return the default if the property does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in Property_Type) return Property_Type;
-- Set the property value
procedure Set (Self : in out Manager'Class;
Name : in String;
Value : in Property_Type);
end Util.Properties.Discrete;
|
Fix header style
|
Fix header style
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0776c81debaaba77b595def843b8eec77f49c5b0
|
src/asf-routes.ads
|
src/asf-routes.ads
|
-----------------------------------------------------------------------
-- asf-routes -- Request routing
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Beans.Basic;
with EL.Expressions;
with EL.Contexts;
package ASF.Routes is
type Route_Type is limited interface;
type Route_Type_Access is access all Route_Type'Class;
-- The <tt>Route_Context_Type</tt> defines the context information after a path
-- has been routed.
type Route_Context_Type is tagged limited private;
-- Get path information after the routing.
function Get_Path_Info (Context : in Route_Context_Type) return String;
-- Return the route associated with the resolved route context.
function Get_Route (Context : in Route_Context_Type) return Route_Type_Access;
-- Inject the parameters that have been extracted from the path according
-- to the selected route.
procedure Inject_Parameters (Context : in Route_Context_Type;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- The <tt>Router_Type</tt> registers the different routes with their rules and
-- resolves a path into a route context information.
type Router_Type is new Ada.Finalization.Limited_Controlled with private;
type Router_Type_Access is access all Router_Type'Class;
-- Add a route associated with the given path pattern. The pattern is split into components.
-- Some path components can be a fixed string (/home) and others can be variable.
-- When a path component is variable, the value can be retrieved from the route context.
procedure Add_Route (Router : in out Router_Type;
Pattern : in String;
To : in Route_Type_Access;
ELContext : in EL.Contexts.ELContext'Class);
-- Build the route context from the given path by looking at the different routes registered
-- in the router with <tt>Add_Route</tt>.
procedure Find_Route (Router : in Router_Type;
Path : in String;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Router : in Router_Type;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
private
type String_Access is access all String;
type Route_Node_Type;
type Route_Node_Access is access all Route_Node_Type'Class;
type Route_Match_Type is (NO_MATCH, MAYBE_MATCH, WILDCARD_MATCH, YES_MATCH);
type Route_Node_Type is abstract tagged limited record
Next_Route : Route_Node_Access;
Children : Route_Node_Access;
Route : Route_Type_Access;
end record;
-- Inject the parameter that was extracted from the path.
procedure Inject_Parameter (Node : in Route_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is abstract;
-- Check if the route node accepts the given path component.
function Matches (Node : in Route_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is abstract;
-- Return the component path pattern that this route node represents.
-- Example: 'index.html', '#{user.id}', ':id'
function Get_Pattern (Node : in Route_Node_Type) return String is abstract;
-- Find recursively a match on the given route sub-tree. The match must start at the position
-- <tt>First</tt> in the path up to the last path position. While the path components are
-- checked, the route context is populated with variable components. When the full path
-- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance.
procedure Find_Match (Node : in Route_Node_Type;
Path : in String;
First : in Natural;
Match : out Route_Match_Type;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Node : in Route_Node_Type;
Path : in String;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
-- A fixed path component identification.
type Path_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : aliased String (1 .. Len);
end record;
type Path_Node_Access is access all Path_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns YES_MATCH if the name corresponds exactly to the node's name.
overriding
function Matches (Node : in Path_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, 'Name').
overriding
function Get_Pattern (Node : in Path_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in Path_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is null;
-- A variable path component whose value is injected in an Ada bean using the EL expression.
-- The route node is created each time an EL expression is found in the route pattern.
-- Example: /home/#{user.id}/index.html
-- In this example, the EL expression refers to <tt>user.id</tt>.
type EL_Node_Type is new Route_Node_Type with record
Value : EL.Expressions.Value_Expression;
end record;
type EL_Node_Access is access all EL_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in EL_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, the EL expr).
overriding
function Get_Pattern (Node : in EL_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in EL_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- A variable path component which can be injected in an Ada bean.
-- Example: /home/:id/view.html
-- The path component represented by <tt>:id</tt> is injected in the Ada bean object
-- passed to the <tt>Inject_Parameters</tt> procedure.
type Param_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : String (1 .. Len);
end record;
type Param_Node_Access is access all Param_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Param_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, Name).
overriding
function Get_Pattern (Node : in Param_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in Param_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
type Extension_Node_Type (Len : Natural) is new Route_Node_Type with record
Ext : String (1 .. Len);
end record;
type Extension_Node_Access is access all Extension_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Extension_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *.Ext).
overriding
function Get_Pattern (Node : in Extension_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in Extension_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is null;
-- Describes a variable path component whose value must be injected in an Ada bean.
type Route_Param_Type is limited record
Route : Route_Node_Access;
First : Natural := 0;
Last : Natural := 0;
end record;
type Route_Param_Array is array (Positive range <>) of Route_Param_Type;
MAX_ROUTE_PARAMS : constant Positive := 10;
type Route_Context_Type is limited new Ada.Finalization.Limited_Controlled with record
Route : Route_Type_Access;
Path : String_Access;
Params : Route_Param_Array (1 .. MAX_ROUTE_PARAMS);
Count : Natural := 0;
end record;
-- Release the storage held by the route context.
overriding
procedure Finalize (Context : in out Route_Context_Type);
type Router_Type is new Ada.Finalization.Limited_Controlled with record
Route : aliased Path_Node_Type (Len => 0);
end record;
-- Release the storage held by the router.
overriding
procedure Finalize (Router : in out Router_Type);
end ASF.Routes;
|
-----------------------------------------------------------------------
-- asf-routes -- Request routing
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Beans.Basic;
with EL.Expressions;
with EL.Contexts;
package ASF.Routes is
type Route_Type is limited interface;
type Route_Type_Access is access all Route_Type'Class;
-- The <tt>Route_Context_Type</tt> defines the context information after a path
-- has been routed.
type Route_Context_Type is tagged limited private;
-- Get path information after the routing.
function Get_Path_Info (Context : in Route_Context_Type) return String;
-- Return the route associated with the resolved route context.
function Get_Route (Context : in Route_Context_Type) return Route_Type_Access;
-- Inject the parameters that have been extracted from the path according
-- to the selected route.
procedure Inject_Parameters (Context : in Route_Context_Type;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- The <tt>Router_Type</tt> registers the different routes with their rules and
-- resolves a path into a route context information.
type Router_Type is new Ada.Finalization.Limited_Controlled with private;
type Router_Type_Access is access all Router_Type'Class;
-- Add a route associated with the given path pattern. The pattern is split into components.
-- Some path components can be a fixed string (/home) and others can be variable.
-- When a path component is variable, the value can be retrieved from the route context.
procedure Add_Route (Router : in out Router_Type;
Pattern : in String;
To : in Route_Type_Access;
ELContext : in EL.Contexts.ELContext'Class);
-- Build the route context from the given path by looking at the different routes registered
-- in the router with <tt>Add_Route</tt>.
procedure Find_Route (Router : in Router_Type;
Path : in String;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Router : in Router_Type;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
private
type String_Access is access all String;
type Route_Node_Type;
type Route_Node_Access is access all Route_Node_Type'Class;
type Route_Match_Type is (NO_MATCH, MAYBE_MATCH, WILDCARD_MATCH, YES_MATCH);
type Route_Node_Type is abstract tagged limited record
Next_Route : Route_Node_Access;
Children : Route_Node_Access;
Route : Route_Type_Access;
end record;
-- Inject the parameter that was extracted from the path.
procedure Inject_Parameter (Node : in Route_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is null;
-- Check if the route node accepts the given path component.
function Matches (Node : in Route_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is abstract;
-- Return the component path pattern that this route node represents.
-- Example: 'index.html', '#{user.id}', ':id'
function Get_Pattern (Node : in Route_Node_Type) return String is abstract;
-- Find recursively a match on the given route sub-tree. The match must start at the position
-- <tt>First</tt> in the path up to the last path position. While the path components are
-- checked, the route context is populated with variable components. When the full path
-- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance.
procedure Find_Match (Node : in Route_Node_Type;
Path : in String;
First : in Natural;
Match : out Route_Match_Type;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Node : in Route_Node_Type;
Path : in String;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
-- A fixed path component identification.
type Path_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : aliased String (1 .. Len);
end record;
type Path_Node_Access is access all Path_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns YES_MATCH if the name corresponds exactly to the node's name.
overriding
function Matches (Node : in Path_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, 'Name').
overriding
function Get_Pattern (Node : in Path_Node_Type) return String;
-- A variable path component whose value is injected in an Ada bean using the EL expression.
-- The route node is created each time an EL expression is found in the route pattern.
-- Example: /home/#{user.id}/index.html
-- In this example, the EL expression refers to <tt>user.id</tt>.
type EL_Node_Type is new Route_Node_Type with record
Value : EL.Expressions.Value_Expression;
end record;
type EL_Node_Access is access all EL_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in EL_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, the EL expr).
overriding
function Get_Pattern (Node : in EL_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in EL_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- A variable path component which can be injected in an Ada bean.
-- Example: /home/:id/view.html
-- The path component represented by <tt>:id</tt> is injected in the Ada bean object
-- passed to the <tt>Inject_Parameters</tt> procedure.
type Param_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : String (1 .. Len);
end record;
type Param_Node_Access is access all Param_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Param_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, Name).
overriding
function Get_Pattern (Node : in Param_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in Param_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
type Extension_Node_Type (Len : Natural) is new Route_Node_Type with record
Ext : String (1 .. Len);
end record;
type Extension_Node_Access is access all Extension_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Extension_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *.Ext).
overriding
function Get_Pattern (Node : in Extension_Node_Type) return String;
type Wildcard_Node_Type is new Route_Node_Type with null record;
type Wildcard_Node_Access is access all Wildcard_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns WILDCARD_MATCH.
overriding
function Matches (Node : in Wildcard_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *).
overriding
function Get_Pattern (Node : in Wildcard_Node_Type) return String;
-- Describes a variable path component whose value must be injected in an Ada bean.
type Route_Param_Type is limited record
Route : Route_Node_Access;
First : Natural := 0;
Last : Natural := 0;
end record;
type Route_Param_Array is array (Positive range <>) of Route_Param_Type;
MAX_ROUTE_PARAMS : constant Positive := 10;
type Route_Context_Type is limited new Ada.Finalization.Limited_Controlled with record
Route : Route_Type_Access;
Path : String_Access;
Params : Route_Param_Array (1 .. MAX_ROUTE_PARAMS);
Count : Natural := 0;
end record;
-- Release the storage held by the route context.
overriding
procedure Finalize (Context : in out Route_Context_Type);
type Router_Type is new Ada.Finalization.Limited_Controlled with record
Route : aliased Path_Node_Type (Len => 0);
end record;
-- Release the storage held by the router.
overriding
procedure Finalize (Router : in out Router_Type);
end ASF.Routes;
|
Define the Wildcard_Node_Type node to represent a wildcard node (such as /admin/*)
|
Define the Wildcard_Node_Type node to represent a wildcard node (such as /admin/*)
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
49b5317c9ecfc8584c3f7b12a4c8a8b41bb800b7
|
src/asf-routes.ads
|
src/asf-routes.ads
|
-----------------------------------------------------------------------
-- asf-routes -- Request routing
-- Copyright (C) 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Beans.Basic;
with Util.Refs;
with EL.Expressions;
with EL.Contexts;
package ASF.Routes is
type Route_Type is abstract new Util.Refs.Ref_Entity with null record;
type Route_Type_Access is access all Route_Type'Class;
-- function Duplicate (Route : in Route_Type) return Route_Type_Access is abstract;
package Route_Type_Refs is
new Util.Refs.Indefinite_References (Element_Type => Route_Type'Class,
Element_Access => Route_Type_Access);
subtype Route_Type_Ref is Route_Type_Refs.Ref;
-- subtype Route_Type_Access is Route_Type_Refs.Element_Access;
No_Parameter : exception;
type Path_Mode is (FULL, PREFIX, SUFFIX);
-- The <tt>Route_Context_Type</tt> defines the context information after a path
-- has been routed.
type Route_Context_Type is tagged limited private;
-- Get path information after the routing.
function Get_Path (Context : in Route_Context_Type;
Mode : in Path_Mode := FULL) return String;
-- Get the path parameter value for the given parameter index.
-- The <tt>No_Parameter</tt> exception is raised if the parameter does not exist.
function Get_Parameter (Context : in Route_Context_Type;
Index : in Positive) return String;
-- Get the number of path parameters that were extracted for the route.
function Get_Parameter_Count (Context : in Route_Context_Type) return Natural;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
function Get_Path_Pos (Context : in Route_Context_Type) return Natural;
-- Return the route associated with the resolved route context.
function Get_Route (Context : in Route_Context_Type) return Route_Type_Access;
-- Change the context to use a new route.
procedure Change_Route (Context : in out Route_Context_Type;
To : in Route_Type_Access);
-- Inject the parameters that have been extracted from the path according
-- to the selected route.
procedure Inject_Parameters (Context : in Route_Context_Type;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- The <tt>Router_Type</tt> registers the different routes with their rules and
-- resolves a path into a route context information.
type Router_Type is new Ada.Finalization.Limited_Controlled with private;
type Router_Type_Access is access all Router_Type'Class;
-- Add a route associated with the given path pattern. The pattern is split into components.
-- Some path components can be a fixed string (/home) and others can be variable.
-- When a path component is variable, the value can be retrieved from the route context.
-- Once the route path is created, the <tt>Process</tt> procedure is called with the route
-- reference.
procedure Add_Route (Router : in out Router_Type;
Pattern : in String;
ELContext : in EL.Contexts.ELContext'Class;
Process : not null access procedure (Route : in out Route_Type_Ref));
-- Build the route context from the given path by looking at the different routes registered
-- in the router with <tt>Add_Route</tt>.
procedure Find_Route (Router : in Router_Type;
Path : in String;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Router : in Router_Type;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
private
type String_Access is access all String;
type Route_Node_Type;
type Route_Node_Access is access all Route_Node_Type'Class;
-- Describes a variable path component whose value must be injected in an Ada bean.
type Route_Param_Type is limited record
Route : Route_Node_Access;
First : Natural := 0;
Last : Natural := 0;
end record;
type Route_Param_Array is array (Positive range <>) of Route_Param_Type;
type Route_Match_Type is (NO_MATCH, MAYBE_MATCH, WILDCARD_MATCH, EXT_MATCH, YES_MATCH);
type Route_Node_Type is abstract tagged limited record
Next_Route : Route_Node_Access;
Children : Route_Node_Access;
Route : Route_Type_Ref;
end record;
-- Inject the parameter that was extracted from the path.
procedure Inject_Parameter (Node : in Route_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is null;
-- Check if the route node accepts the given path component.
function Matches (Node : in Route_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is abstract;
-- Return the component path pattern that this route node represents.
-- Example: 'index.html', '#{user.id}', ':id'
function Get_Pattern (Node : in Route_Node_Type) return String is abstract;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
function Get_Path_Pos (Node : in Route_Node_Type;
Param : in Route_Param_Type) return Natural;
-- Find recursively a match on the given route sub-tree. The match must start at the position
-- <tt>First</tt> in the path up to the last path position. While the path components are
-- checked, the route context is populated with variable components. When the full path
-- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance.
procedure Find_Match (Node : in Route_Node_Type;
Path : in String;
First : in Natural;
Match : out Route_Match_Type;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Node : in Route_Node_Type;
Path : in String;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Access));
-- A fixed path component identification.
type Path_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : aliased String (1 .. Len);
end record;
type Path_Node_Access is access all Path_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns YES_MATCH if the name corresponds exactly to the node's name.
overriding
function Matches (Node : in Path_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, 'Name').
overriding
function Get_Pattern (Node : in Path_Node_Type) return String;
-- A variable path component whose value is injected in an Ada bean using the EL expression.
-- The route node is created each time an EL expression is found in the route pattern.
-- Example: /home/#{user.id}/index.html
-- In this example, the EL expression refers to <tt>user.id</tt>.
type EL_Node_Type is new Route_Node_Type with record
Value : EL.Expressions.Value_Expression;
end record;
type EL_Node_Access is access all EL_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in EL_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, the EL expr).
overriding
function Get_Pattern (Node : in EL_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in EL_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- A variable path component which can be injected in an Ada bean.
-- Example: /home/:id/view.html
-- The path component represented by <tt>:id</tt> is injected in the Ada bean object
-- passed to the <tt>Inject_Parameters</tt> procedure.
type Param_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : String (1 .. Len);
end record;
type Param_Node_Access is access all Param_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Param_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, Name).
overriding
function Get_Pattern (Node : in Param_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in Param_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
type Extension_Node_Type (Len : Natural) is new Route_Node_Type with record
Ext : String (1 .. Len);
end record;
type Extension_Node_Access is access all Extension_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Extension_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *.Ext).
overriding
function Get_Pattern (Node : in Extension_Node_Type) return String;
type Wildcard_Node_Type is new Route_Node_Type with null record;
type Wildcard_Node_Access is access all Wildcard_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns WILDCARD_MATCH.
overriding
function Matches (Node : in Wildcard_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *).
overriding
function Get_Pattern (Node : in Wildcard_Node_Type) return String;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
overriding
function Get_Path_Pos (Node : in Wildcard_Node_Type;
Param : in Route_Param_Type) return Natural;
MAX_ROUTE_PARAMS : constant Positive := 10;
type Route_Context_Type is limited new Ada.Finalization.Limited_Controlled with record
Route : Route_Type_Access;
Path : String_Access;
Params : Route_Param_Array (1 .. MAX_ROUTE_PARAMS);
Count : Natural := 0;
end record;
-- Release the storage held by the route context.
overriding
procedure Finalize (Context : in out Route_Context_Type);
type Router_Type is new Ada.Finalization.Limited_Controlled with record
Route : aliased Path_Node_Type (Len => 0);
end record;
-- Release the storage held by the router.
overriding
procedure Finalize (Router : in out Router_Type);
-- Insert the route node at the correct place in the children list
-- according to the rule kind.
procedure Insert (Parent : in Route_Node_Access;
Node : in Route_Node_Access;
Kind : in Route_Match_Type);
end ASF.Routes;
|
-----------------------------------------------------------------------
-- asf-routes -- Request routing
-- Copyright (C) 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Refs;
with EL.Expressions;
with EL.Contexts;
with Servlet.Routes.Servlets;
package ASF.Routes is
type Faces_Route_Type is new Servlet.Routes.Servlets.Servlet_Route_Type with record
View : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Faces_Route_Type_Access is access all Faces_Route_Type'Class;
subtype Route_Type is Servlet.Routes.Route_Type;
subtype Route_Type_Access is Servlet.Routes.Route_Type_Access;
subtype Route_Type_Ref is Servlet.Routes.Route_Type_Ref;
-- subtype Route_Type_Access is Route_Type_Refs.Element_Access;
subtype Route_Context_Type is Servlet.Routes.Route_Context_Type;
package Route_Type_Refs renames Servlet.Routes.Route_Type_Refs;
end ASF.Routes;
|
Package ASF.Routes moved to Servlet.Routes
|
Package ASF.Routes moved to Servlet.Routes
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
80f4e69c2b80c909154350504af13db65a32250e
|
src/util-files.ads
|
src/util-files.ads
|
-----------------------------------------------------------------------
-- Util.Files -- Various File Utility Packages
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Strings.Maps;
with Util.Strings.Vectors;
package Util.Files is
use Ada.Strings.Unbounded;
subtype Direction is Ada.Strings.Direction;
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0);
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String));
-- Read the file with the given path, one line at a time and append each line to
-- the <b>Into</b> vector.
procedure Read_File (Path : in String;
Into : in out Util.Strings.Vectors.Vector);
-- Save the string into a file creating the file if necessary
procedure Write_File (Path : in String;
Content : in String);
-- Save the string into a file creating the file if necessary
procedure Write_File (Path : in String;
Content : in Unbounded_String);
-- Iterate over the search directories defined in <b>Path</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward);
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward);
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
function Find_File_Path (Name : String;
Paths : String) return String;
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map);
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
function Compose (Directory : in String;
Name : in String) return String;
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
function Compose_Path (Paths : in String;
Name : in String) return String;
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
function Get_Relative_Path (From : in String;
To : in String) return String;
end Util.Files;
|
-----------------------------------------------------------------------
-- util-files -- Various File Utility Packages
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Strings.Maps;
with Util.Strings.Vectors;
package Util.Files is
use Ada.Strings.Unbounded;
subtype Direction is Ada.Strings.Direction;
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0);
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String));
-- Read the file with the given path, one line at a time and append each line to
-- the <b>Into</b> vector.
procedure Read_File (Path : in String;
Into : in out Util.Strings.Vectors.Vector);
-- Save the string into a file creating the file if necessary
procedure Write_File (Path : in String;
Content : in String);
-- Save the string into a file creating the file if necessary
procedure Write_File (Path : in String;
Content : in Unbounded_String);
-- Iterate over the search directories defined in <b>Path</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward);
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward);
-- Find the file in one of the search directories. Each search directory
-- is separated by ';' (yes, even on Unix).
-- Returns the path to be used for reading the file.
function Find_File_Path (Name : String;
Paths : String) return String;
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map);
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
function Compose (Directory : in String;
Name : in String) return String;
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';'.
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
function Compose_Path (Paths : in String;
Name : in String) return String;
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
function Get_Relative_Path (From : in String;
To : in String) return String;
end Util.Files;
|
Update the header and invert some if condition as per AdaControl recommendation
|
Update the header and invert some if condition as per AdaControl recommendation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c2edf2c5ec59cad15576d2e6eeefed4a2c075908
|
src/asf-servlets-rest.adb
|
src/asf-servlets-rest.adb
|
-----------------------------------------------------------------------
-- asf-servlets-rest -- REST servlet
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Rest;
with ASF.Applications;
with ASF.Streams.JSON;
with Util.Streams.Texts;
with Util.Serialize.IO.JSON;
with ASF.Routes.Servlets.Rest;
package body ASF.Servlets.Rest is
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Rest_Servlet;
Context : in Servlet_Registry'Class) is
pragma Unreferenced (Context);
Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
if Ctx.all in ASF.Applications.Main.Application'Class then
Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access;
end if;
end Initialize;
-- ------------------------------
-- Receives standard HTTP requests from the public service method and dispatches
-- them to the Do_XXX methods defined in this class. This method is an HTTP-specific
-- version of the Servlet.service(Request, Response) method. There's no need
-- to override this method.
-- ------------------------------
overriding
procedure Service (Server : in Rest_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
Method : constant String := Request.Get_Method;
begin
if Method = "GET" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.GET, Request, Response);
elsif Method = "POST" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response);
elsif Method = "PUT" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.PUT, Request, Response);
elsif Method = "DELETE" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.DELETE, Request, Response);
elsif Method = "HEAD" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response);
elsif Method = "OPTIONS" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.HEAD, Request, Response);
elsif Method = "TRACE" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.TRACE, Request, Response);
elsif Method = "CONNECT" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.CONNECT, Request, Response);
else
Response.Send_Error (Responses.SC_NOT_IMPLEMENTED);
end if;
end Service;
procedure Dispatch (Server : in Rest_Servlet;
Method : in ASF.Rest.Method_Type;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use type ASF.Routes.Route_Type_Access;
use type ASF.Routes.Servlets.Rest.API_Route_Type;
use type ASF.Rest.Descriptor_Access;
Route : constant ASF.Routes.Route_Type_Access := Request.Get_Route;
begin
if Route = null or else not (Route.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then
Response.Set_Status (ASF.Responses.SC_NOT_FOUND);
return;
end if;
declare
Api : constant access ASF.Routes.Servlets.Rest.API_Route_Type
:= ASF.Routes.Servlets.Rest.API_Route_Type (Route.all)'Access;
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
Stream : ASF.Streams.JSON.Print_Stream;
begin
if Api.Descriptors (Method) = null then
Response.Set_Status (ASF.Responses.SC_NOT_FOUND);
return;
end if;
ASF.Streams.JSON.Initialize (Stream, Output);
Api.Descriptors (Method).Dispatch (Request, Response, Stream);
end;
end Dispatch;
function Create_Route (Registry : in ASF.Servlets.Servlet_Registry;
Name : in String)
return ASF.Routes.Servlets.Rest.API_Route_Type_Access is
Pos : constant Servlet_Maps.Cursor := Registry.Servlets.Find (Name);
Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access;
begin
if not Servlet_Maps.Has_Element (Pos) then
-- Log.Error ("No servlet {0}", Name);
raise Servlet_Error with "No servlet " & Name;
end if;
Result := new ASF.Routes.Servlets.Rest.API_Route_Type;
Result.Servlet := Servlet_Maps.Element (Pos);
return Result;
end Create_Route;
end ASF.Servlets.Rest;
|
-----------------------------------------------------------------------
-- asf-servlets-rest -- REST servlet
-- 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 ASF.Applications;
with ASF.Streams.JSON;
with Util.Streams.Texts;
with Util.Serialize.IO.JSON;
package body ASF.Servlets.Rest is
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Rest_Servlet;
Context : in Servlet_Registry'Class) is
pragma Unreferenced (Context);
Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
if Ctx.all in ASF.Applications.Main.Application'Class then
Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access;
end if;
end Initialize;
-- ------------------------------
-- Receives standard HTTP requests from the public service method and dispatches
-- them to the Do_XXX methods defined in this class. This method is an HTTP-specific
-- version of the Servlet.service(Request, Response) method. There's no need
-- to override this method.
-- ------------------------------
overriding
procedure Service (Server : in Rest_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
Method : constant String := Request.Get_Method;
begin
if Method = "GET" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.GET, Request, Response);
elsif Method = "POST" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response);
elsif Method = "PUT" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.PUT, Request, Response);
elsif Method = "DELETE" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.DELETE, Request, Response);
elsif Method = "HEAD" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response);
elsif Method = "OPTIONS" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.HEAD, Request, Response);
elsif Method = "TRACE" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.TRACE, Request, Response);
elsif Method = "CONNECT" then
Rest_Servlet'Class (Server).Dispatch (ASF.Rest.CONNECT, Request, Response);
else
Response.Send_Error (Responses.SC_NOT_IMPLEMENTED);
end if;
end Service;
procedure Dispatch (Server : in Rest_Servlet;
Method : in ASF.Rest.Method_Type;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server);
use type ASF.Routes.Route_Type_Access;
use type ASF.Routes.Servlets.Rest.API_Route_Type;
use type ASF.Rest.Descriptor_Access;
Route : constant ASF.Routes.Route_Type_Access := Request.Get_Route;
begin
if Route = null or else not (Route.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then
Response.Set_Status (ASF.Responses.SC_NOT_FOUND);
return;
end if;
declare
Api : constant access ASF.Routes.Servlets.Rest.API_Route_Type
:= ASF.Routes.Servlets.Rest.API_Route_Type (Route.all)'Access;
Desc : constant ASF.Rest.Descriptor_Access := Api.Descriptors (Method);
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
Stream : ASF.Streams.JSON.Print_Stream;
begin
if Desc = null then
Response.Set_Status (ASF.Responses.SC_NOT_FOUND);
return;
end if;
-- if not App.Has_Permission (Desc.Permission) then
-- Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
-- return;
-- end if;
ASF.Streams.JSON.Initialize (Stream, Output);
Api.Descriptors (Method).Dispatch (Request, Response, Stream);
end;
end Dispatch;
function Create_Route (Registry : in ASF.Servlets.Servlet_Registry;
Name : in String)
return ASF.Routes.Servlets.Rest.API_Route_Type_Access is
Pos : constant Servlet_Maps.Cursor := Registry.Servlets.Find (Name);
Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access;
begin
if not Servlet_Maps.Has_Element (Pos) then
-- Log.Error ("No servlet {0}", Name);
raise Servlet_Error with "No servlet " & Name;
end if;
Result := new ASF.Routes.Servlets.Rest.API_Route_Type;
Result.Servlet := Servlet_Maps.Element (Pos);
return Result;
end Create_Route;
-- Create a route for the REST API.
function Create_Route (Servlet : in ASF.Servlets.Servlet_Access)
return ASF.Routes.Servlets.Rest.API_Route_Type_Access is
Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access;
begin
Result := new ASF.Routes.Servlets.Rest.API_Route_Type;
Result.Servlet := Servlet;
return Result;
end Create_Route;
end ASF.Servlets.Rest;
|
Implement the Create_Route function
|
Implement the Create_Route function
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
bb50d2141041e0d4f364aa9324e8851f07a7c11a
|
src/gen-artifacts-xmi.ads
|
src/gen-artifacts-xmi.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012, 2013, 2014, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
with Util.Strings.Sets;
-- 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;
Is_Predefined : in Boolean := False);
private
-- Read the UML profiles that are referenced by the current models.
-- The UML profiles are installed in the UML config directory for dynamo's installation.
procedure Read_Profiles (Handler : in out Artifact;
Context : in out Generator'Class);
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
-- A set of profiles that are necessary for the model definitions.
Profiles : aliased Util.Strings.Sets.Set;
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;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Version_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;
Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Generator_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Literal_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Length_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;
Limited_Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Stereotype which triggers the generation of serialization.
Serialize_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, 2013, 2014, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
with Util.Strings.Sets;
-- 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;
Is_Predefined : in Boolean := False);
private
-- Read the UML profiles that are referenced by the current models.
-- The UML profiles are installed in the UML config directory for dynamo's installation.
procedure Read_Profiles (Handler : in out Artifact;
Context : in out Generator'Class);
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
-- A set of profiles that are necessary for the model definitions.
Profiles : aliased Util.Strings.Sets.Set;
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;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Auditable_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;
Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Generator_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Literal_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Length_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;
Limited_Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Stereotype which triggers the generation of serialization.
Serialize_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
Add the Auditable_Stereotype member to the Artifact type
|
Add the Auditable_Stereotype member to the Artifact type
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
5f94f1b999f1d5af2099d275b120a4f91c04b7bb
|
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 `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;
|
-----------------------------------------------------------------------
-- 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;
Queries : ADO.Queries.Query_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 a Queries member to the session factory to get access to the query manager
|
Add a Queries member to the session factory to get access to the query manager
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
add2c1abdf08d2ea5c1886596991326cac8e7827
|
src/util-serialize-tools.adb
|
src/util-serialize-tools.adb
|
-----------------------------------------------------------------------
-- util-serialize-tools -- Tools to Serialize objects in various formats
-- 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.Containers;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
package body Util.Serialize.Tools is
type Object_Field is (FIELD_NAME, FIELD_VALUE);
type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class;
type Object_Mapper_Context is record
Map : Object_Map_Access;
Name : Util.Beans.Objects.Object;
end record;
type Object_Mapper_Context_Access is access all Object_Mapper_Context;
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_VALUE =>
Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value);
Into.Name := Util.Beans.Objects.Null_Object;
end case;
end Set_Member;
package Object_Mapper is new
Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context,
Element_Type_Access => Object_Mapper_Context_Access,
Fields => Object_Field,
Set_Member => Set_Member);
JSON_Mapping : aliased Object_Mapper.Mapper;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b>
-- JSON stream. Use the <b>Name</b> as the name of the JSON object.
-- -----------------------
procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream'Class;
Name : in String;
Map : in Util.Beans.Objects.Maps.Map) is
use type Ada.Containers.Count_Type;
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Output.Start_Entity (Name => "");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_Attribute (Name => "value",
Value => Value);
Output.End_Entity (Name => "");
end Write;
begin
if Map.Length > 0 then
declare
Iter : Util.Beans.Objects.Maps.Cursor := Map.First;
begin
Output.Start_Array (Name => Name);
while Util.Beans.Objects.Maps.Has_Element (Iter) loop
Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access);
Util.Beans.Objects.Maps.Next (Iter);
end loop;
Output.End_Array (Name => Name);
end;
end if;
end To_JSON;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into an XML stream.
-- Returns the JSON string that contains a serialization of the object maps.
-- -----------------------
function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is
use type Ada.Containers.Count_Type;
begin
if Map.Length = 0 then
return "";
end if;
declare
Buffer : aliased Util.Streams.Texts.Print_Stream;
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Size => 10000);
Output.Initialize (Buffer'Unchecked_Access);
Output.Start_Document;
To_JSON (Output, "params", Map);
Output.End_Document;
return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Buffer));
end;
end To_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values. The object map passed in <b>Map</b> can contain existing values.
-- They will be overriden by the JSON values.
-- -----------------------
procedure From_JSON (Content : in String;
Map : in out Util.Beans.Objects.Maps.Map) is
Parser : Util.Serialize.IO.JSON.Parser;
Context : aliased Object_Mapper_Context;
begin
if Content'Length > 0 then
Context.Map := Map'Unchecked_Access;
Parser.Add_Mapping ("/params", JSON_Mapping'Access);
Object_Mapper.Set_Context (Parser, Context'Unchecked_Access);
Parser.Parse_String (Content);
end if;
end From_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values.
-- Returns the object map that was restored.
-- -----------------------
function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is
Result : Util.Beans.Objects.Maps.Map;
begin
From_JSON (Content, Result);
return Result;
end From_JSON;
begin
JSON_Mapping.Add_Mapping ("name", FIELD_NAME);
JSON_Mapping.Add_Mapping ("value", FIELD_VALUE);
end Util.Serialize.Tools;
|
-----------------------------------------------------------------------
-- util-serialize-tools -- Tools to Serialize objects in various formats
-- Copyright (C) 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Mappers.Record_Mapper;
package body Util.Serialize.Tools is
type Object_Field is (FIELD_NAME, FIELD_VALUE);
type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class;
type Object_Mapper_Context is record
Map : Object_Map_Access;
Name : Util.Beans.Objects.Object;
end record;
type Object_Mapper_Context_Access is access all Object_Mapper_Context;
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Object_Mapper_Context;
Field : in Object_Field;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_VALUE =>
Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value);
Into.Name := Util.Beans.Objects.Null_Object;
end case;
end Set_Member;
package Object_Mapper is new
Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context,
Element_Type_Access => Object_Mapper_Context_Access,
Fields => Object_Field,
Set_Member => Set_Member);
JSON_Mapping : aliased Object_Mapper.Mapper;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b>
-- JSON stream. Use the <b>Name</b> as the name of the JSON object.
-- -----------------------
procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream'Class;
Name : in String;
Map : in Util.Beans.Objects.Maps.Map) is
use type Ada.Containers.Count_Type;
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Write (Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Output.Start_Entity (Name => "");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_Attribute (Name => "value",
Value => Value);
Output.End_Entity (Name => "");
end Write;
begin
if Map.Length > 0 then
declare
Iter : Util.Beans.Objects.Maps.Cursor := Map.First;
begin
Output.Start_Array (Name => Name);
while Util.Beans.Objects.Maps.Has_Element (Iter) loop
Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access);
Util.Beans.Objects.Maps.Next (Iter);
end loop;
Output.End_Array (Name => Name);
end;
end if;
end To_JSON;
-- -----------------------
-- Serialize the objects defined in the object map <b>Map</b> into an XML stream.
-- Returns the JSON string that contains a serialization of the object maps.
-- -----------------------
function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is
use type Ada.Containers.Count_Type;
begin
if Map.Length = 0 then
return "";
end if;
declare
Buffer : aliased Util.Streams.Texts.Print_Stream;
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Size => 10000);
Output.Initialize (Buffer'Unchecked_Access);
Output.Start_Document;
To_JSON (Output, "params", Map);
Output.End_Document;
return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Buffer));
end;
end To_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values. The object map passed in <b>Map</b> can contain existing values.
-- They will be overriden by the JSON values.
-- -----------------------
procedure From_JSON (Content : in String;
Map : in out Util.Beans.Objects.Maps.Map) is
Parser : Util.Serialize.IO.JSON.Parser;
Context : aliased Object_Mapper_Context;
begin
if Content'Length > 0 then
Context.Map := Map'Unchecked_Access;
Parser.Add_Mapping ("**", JSON_Mapping'Access);
Object_Mapper.Set_Context (Parser, Context'Unchecked_Access);
Parser.Parse_String (Content);
end if;
end From_JSON;
-- -----------------------
-- Deserializes the JSON content passed in <b>Content</b> and restore the object map
-- with their values.
-- Returns the object map that was restored.
-- -----------------------
function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is
Result : Util.Beans.Objects.Maps.Map;
begin
From_JSON (Content, Result);
return Result;
end From_JSON;
begin
JSON_Mapping.Add_Mapping ("name", FIELD_NAME);
JSON_Mapping.Add_Mapping ("value", FIELD_VALUE);
end Util.Serialize.Tools;
|
Update the From_JSON mapping for the parser
|
Update the From_JSON mapping for the parser
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ebae7979b6600b7adf9c89ebdbde9a29d37d85e9
|
src/babel-strategies.ads
|
src/babel-strategies.ads
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Listeners;
with Babel.Files;
with Babel.Files.Queues;
with Babel.Files.Buffers;
with Babel.Stores;
with Babel.Filters;
with Babel.Base;
with Babel.Base.Text;
package Babel.Strategies is
type Strategy_Type is abstract tagged limited private;
type Strategy_Type_Access is access all Strategy_Type'Class;
-- Allocate a buffer to read the file content.
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access;
-- Release the buffer that was allocated by Allocate_Buffer.
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access);
-- Returns true if there is a directory that must be processed by the current strategy.
function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract;
-- Get the next directory that must be processed by the strategy.
procedure Peek_Directory (Strategy : in out Strategy_Type;
Directory : out Babel.Files.Directory_Type) is abstract;
-- Scan the directory
procedure Scan (Strategy : in out Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class);
-- Scan the directories which are defined in the directory queue and
-- use the file container to scan the files and directories.
procedure Scan (Strategy : in out Strategy_Type;
Queue : in out Babel.Files.Queues.Directory_Queue;
Container : in out Babel.Files.File_Container'Class);
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Into : in Babel.Files.Buffers.Buffer_Access);
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in Babel.Files.Buffers.Buffer_Access);
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in out Strategy_Type;
File : in Babel.Files.File_Type;
Content : in out Babel.Files.Buffers.Buffer_Access);
procedure Execute (Strategy : in out Strategy_Type) is abstract;
-- Set the file filters that will be used when scanning the read store.
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access);
-- Set the read and write stores that the strategy will use.
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access);
-- Set the buffer pool to be used by Allocate_Buffer.
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
-- Set the listeners to inform about changes.
procedure Set_Listeners (Strategy : in out Strategy_Type;
Listeners : access Util.Listeners.List);
-- Set the database for use by the strategy.
procedure Set_Database (Strategy : in out Strategy_Type;
Database : in Babel.Base.Database_Access);
private
type Strategy_Type is abstract tagged limited record
Read_Store : Babel.Stores.Store_Type_Access;
Write_Store : Babel.Stores.Store_Type_Access;
Filters : Babel.Filters.Filter_Type_Access;
Buffers : Babel.Files.Buffers.Buffer_Pool_Access;
Listeners : access Util.Listeners.List;
-- Database : Babel.Base.Database_Access;
Database : Babel.Base.Text.Text_Database;
end record;
end Babel.Strategies;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Listeners;
with Babel.Files;
with Babel.Files.Queues;
with Babel.Files.Buffers;
with Babel.Streams.Refs;
with Babel.Stores;
with Babel.Filters;
with Babel.Base;
with Babel.Base.Text;
package Babel.Strategies is
type Strategy_Type is abstract tagged limited private;
type Strategy_Type_Access is access all Strategy_Type'Class;
-- Allocate a buffer to read the file content.
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access;
-- Release the buffer that was allocated by Allocate_Buffer.
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access);
-- Returns true if there is a directory that must be processed by the current strategy.
function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract;
-- Get the next directory that must be processed by the strategy.
procedure Peek_Directory (Strategy : in out Strategy_Type;
Directory : out Babel.Files.Directory_Type) is abstract;
-- Scan the directory
procedure Scan (Strategy : in out Strategy_Type;
Directory : in Babel.Files.Directory_Type;
Container : in out Babel.Files.File_Container'Class);
-- Scan the directories which are defined in the directory queue and
-- use the file container to scan the files and directories.
procedure Scan (Strategy : in out Strategy_Type;
Queue : in out Babel.Files.Queues.Directory_Queue;
Container : in out Babel.Files.File_Container'Class);
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Into : in Babel.Files.Buffers.Buffer_Access);
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in Babel.Files.Buffers.Buffer_Access);
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in out Strategy_Type;
File : in Babel.Files.File_Type;
Content : in out Babel.Files.Buffers.Buffer_Access);
procedure Execute (Strategy : in out Strategy_Type) is abstract;
-- Set the file filters that will be used when scanning the read store.
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access);
-- Set the read and write stores that the strategy will use.
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access);
-- Set the buffer pool to be used by Allocate_Buffer.
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
-- Set the listeners to inform about changes.
procedure Set_Listeners (Strategy : in out Strategy_Type;
Listeners : access Util.Listeners.List);
-- Set the database for use by the strategy.
procedure Set_Database (Strategy : in out Strategy_Type;
Database : in Babel.Base.Database_Access);
private
type Strategy_Type is abstract tagged limited record
Read_Store : Babel.Stores.Store_Type_Access;
Write_Store : Babel.Stores.Store_Type_Access;
Filters : Babel.Filters.Filter_Type_Access;
Buffers : Babel.Files.Buffers.Buffer_Pool_Access;
Listeners : access Util.Listeners.List;
-- Database : Babel.Base.Database_Access;
Database : Babel.Base.Text.Text_Database;
end record;
end Babel.Strategies;
|
Use the Babel.Streams.Refs package
|
Use the Babel.Streams.Refs package
|
Ada
|
apache-2.0
|
stcarrez/babel
|
8ea449f59c67adde46f40e4b2e3dcf8cc75aaa5d
|
src/wiki-utils.adb
|
src/wiki-utils.adb
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
with Wiki.Render.Text;
with Wiki.Render.Html;
with Wiki.Writers.Builders;
package body 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.Parsers.Wiki_Syntax_Type) return String is
Writer : aliased Wiki.Writers.Builders.Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Writer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax);
return Writer.To_String;
end To_Html;
-- ------------------------------
-- Render the wiki text according to the wiki syntax in text into a string.
-- Wiki formatting and decoration are removed.
-- ------------------------------
function To_Text (Text : in Wide_Wide_String;
Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is
Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax);
return Writer.To_String;
end To_Text;
end Wiki.Utils;
|
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
with Wiki.Render.Text;
with Wiki.Render.Html;
with Wiki.Writers.Builders;
package body 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.Parsers.Wiki_Syntax_Type) return String is
Writer : aliased Wiki.Writers.Builders.Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax);
return Writer.To_String;
end To_Html;
-- ------------------------------
-- Render the wiki text according to the wiki syntax in text into a string.
-- Wiki formatting and decoration are removed.
-- ------------------------------
function To_Text (Text : in Wide_Wide_String;
Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is
Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
begin
Renderer.Set_Writer (Writer'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax);
return Writer.To_String;
end To_Text;
end Wiki.Utils;
|
Use the Html_Renderer type
|
Use the Html_Renderer type
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
1cb961f3a2e830bae0de6de383695ddc22714aa5
|
src/asf-servlets-faces.adb
|
src/asf-servlets-faces.adb
|
-----------------------------------------------------------------------
-- asf.servlets.faces -- Faces servlet
-- Copyright (C) 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 ASF.Applications;
package body ASF.Servlets.Faces is
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
procedure Initialize (Server : in out Faces_Servlet;
Context : in Servlet_Registry'Class) is
pragma Unreferenced (Context);
Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
if Ctx.all in ASF.Applications.Main.Application'Class then
Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access;
end if;
end Initialize;
-- 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"
procedure Do_Get (Server : in Faces_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
URI : constant String := Request.Get_Path_Info;
begin
Server.App.Dispatch (Page => URI,
Request => Request,
Response => Response);
end Do_Get;
-- Called by the server (via the service method) to allow a servlet to handle
-- a POST request. The HTTP POST method allows the client to send data of unlimited
-- length to the Web server a single time and is useful when posting information
-- such as credit card numbers.
--
-- 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.
--
-- This method does not need to be either safe or idempotent. Operations
-- requested through POST can have side effects for which the user can be held
-- accountable, for example, updating stored data or buying items online.
--
-- If the HTTP POST request is incorrectly formatted, doPost returns
-- an HTTP "Bad Request" message.
procedure Do_Post (Server : in Faces_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
URI : constant String := Request.Get_Path_Info;
begin
Server.App.Dispatch (Page => URI,
Request => Request,
Response => Response);
end Do_Post;
end ASF.Servlets.Faces;
|
-----------------------------------------------------------------------
-- asf.servlets.faces -- Faces servlet
-- Copyright (C) 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
package body ASF.Servlets.Faces is
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Faces_Servlet;
Context : in Servlet_Registry'Class) is
pragma Unreferenced (Context);
Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
if Ctx.all in ASF.Applications.Main.Application'Class then
Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access;
end if;
end Initialize;
-- ------------------------------
-- 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"
-- ------------------------------
procedure Do_Get (Server : in Faces_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
URI : constant String := Request.Get_Servlet_Path;
begin
Server.App.Dispatch (Page => URI,
Request => Request,
Response => Response);
end Do_Get;
-- ------------------------------
-- Called by the server (via the service method) to allow a servlet to handle
-- a POST request. The HTTP POST method allows the client to send data of unlimited
-- length to the Web server a single time and is useful when posting information
-- such as credit card numbers.
--
-- 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.
--
-- This method does not need to be either safe or idempotent. Operations
-- requested through POST can have side effects for which the user can be held
-- accountable, for example, updating stored data or buying items online.
--
-- If the HTTP POST request is incorrectly formatted, doPost returns
-- an HTTP "Bad Request" message.
-- ------------------------------
procedure Do_Post (Server : in Faces_Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
URI : constant String := Request.Get_Servlet_Path;
begin
Server.App.Dispatch (Page => URI,
Request => Request,
Response => Response);
end Do_Post;
end ASF.Servlets.Faces;
|
Use Get_Servlet_Path instead of Get_Path_Info
|
Use Get_Servlet_Path instead of Get_Path_Info
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
14bdde03fb4da1c52ace93a01b09b2919b00b401
|
src/wiki-filters-html.ads
|
src/wiki-filters-html.ads
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Containers.Vectors;
-- === HTML Filters ===
-- The <b>Wiki.Filters.Html</b> package implements a customizable HTML filter that verifies
-- the HTML content embedded in the Wiki text.
--
-- The HTML filter may be declared and configured as follows:
--
-- F : aliased Wiki.Filters.Html.Html_Filter_Type;
-- ...
-- F.Forbidden (Wiki.Filters.Html.SCRIPT_TAG);
-- F.Forbidden (Wiki.Filters.Html.A_TAG);
--
-- The <tt>Set_Document</tt> operation is used to link the HTML filter to a next filter
-- or to the HTML or text renderer:
--
-- F.Set_Document (Renderer'Access);
--
-- The HTML filter is then either inserted as a document for a previous filter or for
-- the wiki parser:
--
-- Wiki.Parsers.Parse (F'Access, Wiki_Text, Syntax);
--
package Wiki.Filters.Html is
use Wiki.Nodes;
-- ------------------------------
-- Filter type
-- ------------------------------
type Html_Filter_Type is new Filter_Type with private;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a link.
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document);
-- Mark the HTML tag as being forbidden.
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being allowed.
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being visible.
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Flush the HTML element that have not yet been closed.
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document);
private
use Wiki.Nodes;
type Tag_Boolean_Array is array (Html_Tag) of Boolean;
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Html_Tag);
subtype Tag_Vector is Tag_Vectors.Vector;
subtype Tag_Cursor is Tag_Vectors.Cursor;
type Html_Filter_Type is new Filter_Type with record
Allowed : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => False,
ROOT_HTML_TAG => False,
HEAD_TAG => False,
BODY_TAG => False,
META_TAG => False,
TITLE_TAG => False,
others => True);
Hidden : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => True,
STYLE_TAG => True,
others => False);
Stack : Tag_Vector;
Hide_Level : Natural := 0;
end record;
end Wiki.Filters.Html;
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Ada.Containers.Vectors;
-- === HTML Filters ===
-- The <b>Wiki.Filters.Html</b> package implements a customizable HTML filter that verifies
-- the HTML content embedded in the Wiki text.
--
-- The HTML filter may be declared and configured as follows:
--
-- F : aliased Wiki.Filters.Html.Html_Filter_Type;
-- ...
-- F.Forbidden (Wiki.Filters.Html.SCRIPT_TAG);
-- F.Forbidden (Wiki.Filters.Html.A_TAG);
--
-- The <tt>Set_Document</tt> operation is used to link the HTML filter to a next filter
-- or to the HTML or text renderer:
--
-- F.Set_Document (Renderer'Access);
--
-- The HTML filter is then either inserted as a document for a previous filter or for
-- the wiki parser:
--
-- Wiki.Parsers.Parse (F'Access, Wiki_Text, Syntax);
--
package Wiki.Filters.Html is
-- ------------------------------
-- Filter type
-- ------------------------------
type Html_Filter_Type is new Filter_Type with private;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a link.
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document);
-- Mark the HTML tag as being forbidden.
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being allowed.
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Mark the HTML tag as being visible.
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag);
-- Flush the HTML element that have not yet been closed.
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document);
private
use Wiki.Nodes;
type Tag_Boolean_Array is array (Html_Tag) of Boolean;
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Html_Tag);
subtype Tag_Vector is Tag_Vectors.Vector;
subtype Tag_Cursor is Tag_Vectors.Cursor;
type Html_Filter_Type is new Filter_Type with record
Allowed : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => False,
ROOT_HTML_TAG => False,
HEAD_TAG => False,
BODY_TAG => False,
META_TAG => False,
TITLE_TAG => False,
others => True);
Hidden : Tag_Boolean_Array := (UNKNOWN_TAG => False,
SCRIPT_TAG => True,
STYLE_TAG => True,
others => False);
Stack : Tag_Vector;
Hide_Level : Natural := 0;
end record;
end Wiki.Filters.Html;
|
Remove use of Wiki.Nodes package
|
Remove use of Wiki.Nodes package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
b49c3365762c921e1e65f87877227399c5fff241
|
awa/regtests/awa-mail-modules-tests.adb
|
awa/regtests/awa-mail-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-mail-module-tests -- Unit tests for Mail module
-- Copyright (C) 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with AWA.Events;
package body AWA.Mail.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Mail.Clients");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message",
Test_Create_Message'Access);
Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (CC:)",
Test_Cc_Message'Access);
Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (BCC:)",
Test_Bcc_Message'Access);
end Add_Tests;
-- ------------------------------
-- Create an email message with the given template and verify its content.
-- ------------------------------
procedure Test_Mail_Message (T : in out Test;
Name : in String) is
use Util.Beans.Objects;
Mail : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module;
Event : AWA.Events.Module_Event;
Props : Util.Beans.Objects.Maps.Map;
begin
T.Assert (Mail /= null, "There is no current mail module");
Props.Insert ("name", To_Object (String '("joe")));
Props.Insert ("email", To_Object (String '("[email protected]")));
Mail.Send_Mail (Template => Name,
Props => Props,
Content => Event);
end Test_Mail_Message;
-- ------------------------------
-- Create an email message and verify its content.
-- ------------------------------
procedure Test_Create_Message (T : in out Test) is
begin
T.Test_Mail_Message ("mail-info.html");
end Test_Create_Message;
-- ------------------------------
-- Create an email message with Cc: and verify its content.
-- ------------------------------
procedure Test_Cc_Message (T : in out Test) is
begin
T.Test_Mail_Message ("mail-cc.html");
end Test_Cc_Message;
-- ------------------------------
-- Create an email message with Bcc: and verify its content.
-- ------------------------------
procedure Test_Bcc_Message (T : in out Test) is
begin
T.Test_Mail_Message ("mail-bcc.html");
end Test_Bcc_Message;
end AWA.Mail.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-mail-module-tests -- Unit tests for Mail module
-- Copyright (C) 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with AWA.Events;
package body AWA.Mail.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Mail.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message",
Test_Create_Message'Access);
Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (CC:)",
Test_Cc_Message'Access);
Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (BCC:)",
Test_Bcc_Message'Access);
end Add_Tests;
-- ------------------------------
-- Create an email message with the given template and verify its content.
-- ------------------------------
procedure Test_Mail_Message (T : in out Test;
Name : in String) is
use Util.Beans.Objects;
Mail : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module;
Event : AWA.Events.Module_Event;
Props : Util.Beans.Objects.Maps.Map;
begin
T.Assert (Mail /= null, "There is no current mail module");
Props.Insert ("name", To_Object (String '("joe")));
Props.Insert ("email", To_Object (String '("[email protected]")));
Mail.Send_Mail (Template => Name,
Props => Props,
Content => Event);
end Test_Mail_Message;
-- ------------------------------
-- Create an email message and verify its content.
-- ------------------------------
procedure Test_Create_Message (T : in out Test) is
begin
T.Test_Mail_Message ("mail-info.html");
end Test_Create_Message;
-- ------------------------------
-- Create an email message with Cc: and verify its content.
-- ------------------------------
procedure Test_Cc_Message (T : in out Test) is
begin
T.Test_Mail_Message ("mail-cc.html");
end Test_Cc_Message;
-- ------------------------------
-- Create an email message with Bcc: and verify its content.
-- ------------------------------
procedure Test_Bcc_Message (T : in out Test) is
begin
T.Test_Mail_Message ("mail-bcc.html");
end Test_Bcc_Message;
end AWA.Mail.Modules.Tests;
|
Fix the name of the test because it is already used by another test
|
Fix the name of the test because it is already used by another test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
63d9b8e932f7e6176a0dbae1c38ba26ef6c12644
|
tools/druss-commands-devices.adb
|
tools/druss-commands-devices.adb
|
-----------------------------------------------------------------------
-- druss-commands-devices -- Print information about the devices
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
with Bbox.API;
with Druss.Gateways;
package body Druss.Commands.Devices is
-- ------------------------------
-- Execute the wifi 'status' command to print the Wifi current status.
-- ------------------------------
procedure Do_List (Command : in Command_Type;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Kind : constant String := Manager.Get (Name & ".devicetype", "");
begin
if Manager.Get (Name & ".active", "") = "0" then
return;
end if;
Console.Start_Row;
Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip);
Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", ""));
Console.Print_Field (F_ETHERNET, Manager.Get (Name & ".macaddress", ""));
Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", ""));
Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".active", ""));
Console.Print_Field (F_DEVTYPE, (if Kind = "STB" then "STB" else ""));
if Link = "Ethernet" then
Console.Print_Field (F_LINK, Link & " port "
& Manager.Get (Name & ".ethernet.logicalport", ""));
else
Console.Print_Field (F_LINK, Link & " RSSI "
& Manager.Get (Name & ".wireless.rssi0", ""));
end if;
Console.End_Row;
end Print_Device;
begin
Gateway.Refresh;
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access);
end Box_Status;
begin
Console.Start_Title;
Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16);
Console.Print_Title (F_IP_ADDR, "Device IP", 16);
Console.Print_Title (F_ETHERNET, "Ethernet", 20);
Console.Print_Title (F_HOSTNAME, "Hostname", 28);
Console.Print_Title (F_DEVTYPE, "Type", 6);
-- Console.Print_Title (F_ACTIVE, "Active", 8);
Console.Print_Title (F_LINK, "Link", 18);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access);
end Do_List;
-- Execute a status command to report information about the Bbox.
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
Command.Do_List (Args, Context);
end Execute;
-- Write the help associated with the command.
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "devices: Print information about the devices");
Console.Notice (N_HELP, "Usage: devices [options]");
Console.Notice (N_HELP, "");
end Help;
end Druss.Commands.Devices;
|
-----------------------------------------------------------------------
-- druss-commands-devices -- Print information about the devices
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
with Bbox.API;
with Druss.Gateways;
package body Druss.Commands.Devices is
-- ------------------------------
-- Execute the wifi 'status' command to print the Wifi current status.
-- ------------------------------
procedure Do_List (Command : in Command_Type;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Command, Args);
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String);
procedure Print_Device (Manager : in Util.Properties.Manager;
Name : in String) is
Link : constant String := Manager.Get (Name & ".link", "");
Kind : constant String := Manager.Get (Name & ".devicetype", "");
begin
if Manager.Get (Name & ".active", "") = "0" then
return;
end if;
Console.Start_Row;
Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip);
Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", ""));
Console.Print_Field (F_ETHERNET, Manager.Get (Name & ".macaddress", ""));
Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", ""));
Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".active", ""));
Console.Print_Field (F_DEVTYPE, (if Kind = "STB" then "STB" else ""));
if Link = "Ethernet" then
Console.Print_Field (F_LINK, Link & " port "
& Manager.Get (Name & ".ethernet.logicalport", ""));
else
Console.Print_Field (F_LINK, Link & " RSSI "
& Manager.Get (Name & ".wireless.rssi0", ""));
end if;
Console.End_Row;
end Print_Device;
begin
Gateway.Refresh;
Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access);
end Box_Status;
begin
Console.Start_Title;
Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16);
Console.Print_Title (F_IP_ADDR, "Device IP", 16);
Console.Print_Title (F_ETHERNET, "Ethernet", 20);
Console.Print_Title (F_HOSTNAME, "Hostname", 28);
Console.Print_Title (F_DEVTYPE, "Type", 6);
-- Console.Print_Title (F_ACTIVE, "Active", 8);
Console.Print_Title (F_LINK, "Link", 18);
Console.End_Title;
Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access);
end Do_List;
-- ------------------------------
-- Execute a status command to report information about the Bbox.
-- ------------------------------
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
begin
Command.Do_List (Args, Context);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is
pragma Unreferenced (Command);
Console : constant Druss.Commands.Consoles.Console_Access := Context.Console;
begin
Console.Notice (N_HELP, "devices: Print information about the devices");
Console.Notice (N_HELP, "Usage: devices [options]");
Console.Notice (N_HELP, "");
end Help;
end Druss.Commands.Devices;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
c5cba876f491278d3424e30ef690d34453e4b57f
|
mat/src/mat-targets-probes.adb
|
mat/src/mat-targets-probes.adb
|
-----------------------------------------------------------------------
-- mat-targets-probes - Definition and Analysis of process start 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.Readers.Marshaller;
package body MAT.Targets.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes");
MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0;
MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1;
MSG_LIBRARY : constant MAT.Events.Targets.Probe_Index_Type := 2;
M_PID : constant MAT.Events.Internal_Reference := 1;
M_EXE : constant MAT.Events.Internal_Reference := 2;
M_HEAP_START : constant MAT.Events.Internal_Reference := 3;
M_HEAP_END : constant MAT.Events.Internal_Reference := 4;
M_END : constant MAT.Events.Internal_Reference := 5;
M_LIBNAME : constant MAT.Events.Internal_Reference := 6;
M_LADDR : constant MAT.Events.Internal_Reference := 7;
M_COUNT : constant MAT.Events.Internal_Reference := 8;
M_TYPE : constant MAT.Events.Internal_Reference := 9;
M_VADDR : constant MAT.Events.Internal_Reference := 10;
M_SIZE : constant MAT.Events.Internal_Reference := 11;
PID_NAME : aliased constant String := "pid";
EXE_NAME : aliased constant String := "exe";
HP_START_NAME : aliased constant String := "hp_start";
HP_END_NAME : aliased constant String := "hp_end";
END_NAME : aliased constant String := "end";
LIBNAME_NAME : aliased constant String := "libname";
LADDR_NAME : aliased constant String := "laddr";
COUNT_NAME : aliased constant String := "count";
TYPE_NAME : aliased constant String := "type";
VADDR_NAME : aliased constant String := "vaddr";
SIZE_NAME : aliased constant String := "size";
Process_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => PID_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_PID),
2 => (Name => EXE_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_EXE),
3 => (Name => HP_START_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START),
4 => (Name => HP_END_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END),
5 => (Name => END_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_END));
Library_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => LIBNAME_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME),
2 => (Name => LADDR_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_LADDR),
3 => (Name => COUNT_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_COUNT),
4 => (Name => TYPE_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_TYPE),
5 => (Name => VADDR_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_VADDR),
6 => (Name => SIZE_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_SIZE));
-- ------------------------------
-- Create a new process after the begin event is received from the event stream.
-- ------------------------------
procedure Create_Process (Probe : in Process_Probe_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Probe.Target.Create_Process (Pid => Pid,
Path => Path,
Process => Probe.Target.Current);
Probe.Target.Process.Events := Probe.Events;
MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory,
Manager => Probe.Manager.all);
end Create_Process;
procedure Probe_Begin (Probe : in Process_Probe_Type;
Id : in MAT.Events.Targets.Probe_Index_Type;
Defs : in MAT.Events.Attribute_Table;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Addr;
Pid : MAT.Types.Target_Process_Ref := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
Heap : MAT.Memory.Region_Info;
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_PID =>
Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind);
when M_EXE =>
Path := MAT.Readers.Marshaller.Get_String (Msg);
when M_HEAP_START =>
Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when M_HEAP_END =>
Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when others =>
MAT.Readers.Marshaller.Skip (Msg, Def.Size);
end case;
end;
end loop;
Heap.Size := Heap.End_Addr - Heap.Start_Addr;
Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]");
Probe.Create_Process (Pid, Path);
Probe.Manager.Read_Message (Msg);
Probe.Manager.Read_Event_Definitions (Msg);
Probe.Target.Process.Memory.Add_Region (Heap);
end Probe_Begin;
overriding
procedure Extract (Probe : in Process_Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type) is
use type MAT.Events.Targets.Probe_Index_Type;
begin
if Event.Index = MSG_BEGIN then
Probe.Probe_Begin (Event.Index, Params.all, Msg);
end if;
end Extract;
procedure Execute (Probe : in Process_Probe_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
null;
end Execute;
-- ------------------------------
-- Register the reader to extract and analyze process events.
-- ------------------------------
procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class;
Probe : in Process_Probe_Type_Access) is
begin
Probe.Manager := Into'Unchecked_Access;
Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN,
Process_Attributes'Access);
Into.Register_Probe (Probe.all'Access, "end", MSG_END,
Process_Attributes'Access);
Into.Register_Probe (Probe.all'Access, "shlib", MSG_LIBRARY,
Library_Attributes'Access);
end Register;
-- ------------------------------
-- Initialize the target object to prepare for reading process events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Process_Probe : constant Process_Probe_Type_Access
:= new Process_Probe_Type;
begin
Process_Probe.Target := Target'Unrestricted_Access;
Process_Probe.Events := Manager.Get_Target_Events;
Register (Manager, Process_Probe);
end Initialize;
end MAT.Targets.Probes;
|
-----------------------------------------------------------------------
-- mat-targets-probes - Definition and Analysis of process start 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 ELF;
with MAT.Readers.Marshaller;
package body MAT.Targets.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Targets.Probes");
MSG_BEGIN : constant MAT.Events.Targets.Probe_Index_Type := 0;
MSG_END : constant MAT.Events.Targets.Probe_Index_Type := 1;
MSG_LIBRARY : constant MAT.Events.Targets.Probe_Index_Type := 2;
M_PID : constant MAT.Events.Internal_Reference := 1;
M_EXE : constant MAT.Events.Internal_Reference := 2;
M_HEAP_START : constant MAT.Events.Internal_Reference := 3;
M_HEAP_END : constant MAT.Events.Internal_Reference := 4;
M_END : constant MAT.Events.Internal_Reference := 5;
M_LIBNAME : constant MAT.Events.Internal_Reference := 6;
M_LADDR : constant MAT.Events.Internal_Reference := 7;
M_COUNT : constant MAT.Events.Internal_Reference := 8;
M_TYPE : constant MAT.Events.Internal_Reference := 9;
M_VADDR : constant MAT.Events.Internal_Reference := 10;
M_SIZE : constant MAT.Events.Internal_Reference := 11;
M_FLAGS : constant MAT.Events.Internal_Reference := 12;
PID_NAME : aliased constant String := "pid";
EXE_NAME : aliased constant String := "exe";
HP_START_NAME : aliased constant String := "hp_start";
HP_END_NAME : aliased constant String := "hp_end";
END_NAME : aliased constant String := "end";
LIBNAME_NAME : aliased constant String := "libname";
LADDR_NAME : aliased constant String := "laddr";
COUNT_NAME : aliased constant String := "count";
TYPE_NAME : aliased constant String := "type";
VADDR_NAME : aliased constant String := "vaddr";
SIZE_NAME : aliased constant String := "size";
FLAGS_NAME : aliased constant String := "flags";
Process_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => PID_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_PID),
2 => (Name => EXE_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_EXE),
3 => (Name => HP_START_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_HEAP_START),
4 => (Name => HP_END_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_HEAP_END),
5 => (Name => END_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_END));
Library_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => LIBNAME_NAME'Access, Size => 0,
Kind => MAT.Events.T_SIZE_T, Ref => M_LIBNAME),
2 => (Name => LADDR_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_LADDR),
3 => (Name => COUNT_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_COUNT),
4 => (Name => TYPE_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_TYPE),
5 => (Name => VADDR_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_VADDR),
6 => (Name => SIZE_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_SIZE),
7 => (Name => FLAGS_NAME'Access, Size => 0,
Kind => MAT.Events.T_FRAME, Ref => M_FLAGS));
-- ------------------------------
-- Create a new process after the begin event is received from the event stream.
-- ------------------------------
procedure Create_Process (Probe : in Process_Probe_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Probe.Target.Create_Process (Pid => Pid,
Path => Path,
Process => Probe.Target.Current);
Probe.Target.Process.Events := Probe.Events;
MAT.Memory.Targets.Initialize (Memory => Probe.Target.Process.Memory,
Manager => Probe.Manager.all);
end Create_Process;
procedure Probe_Begin (Probe : in Process_Probe_Type;
Id : in MAT.Events.Targets.Probe_Index_Type;
Defs : in MAT.Events.Attribute_Table;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Addr;
Pid : MAT.Types.Target_Process_Ref := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
Heap : MAT.Memory.Region_Info;
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_PID =>
Pid := MAT.Readers.Marshaller.Get_Target_Process_Ref (Msg, Def.Kind);
when M_EXE =>
Path := MAT.Readers.Marshaller.Get_String (Msg);
when M_HEAP_START =>
Heap.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when M_HEAP_END =>
Heap.End_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when others =>
MAT.Readers.Marshaller.Skip (Msg, Def.Size);
end case;
end;
end loop;
Heap.Size := Heap.End_Addr - Heap.Start_Addr;
Heap.Path := Ada.Strings.Unbounded.To_Unbounded_String ("[heap]");
Probe.Create_Process (Pid, Path);
Probe.Manager.Read_Message (Msg);
Probe.Manager.Read_Event_Definitions (Msg);
Probe.Target.Process.Memory.Add_Region (Heap);
end Probe_Begin;
-- ------------------------------
-- Extract the information from the 'library' event.
-- ------------------------------
procedure Probe_Library (Probe : in Process_Probe_Type;
Id : in MAT.Events.Targets.Probe_Index_Type;
Defs : in MAT.Events.Attribute_Table;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Addr;
Count : MAT.Types.Target_Size := 0;
Path : Ada.Strings.Unbounded.Unbounded_String;
Heap : MAT.Memory.Region_Info;
Addr : MAT.Types.Target_Addr;
Pos : Natural := Defs'Last + 1;
begin
for I in Defs'Range loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_COUNT =>
Count := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind);
Pos := I + 1;
exit;
when M_LIBNAME =>
Path := MAT.Readers.Marshaller.Get_String (Msg);
when M_LADDR =>
Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when others =>
MAT.Readers.Marshaller.Skip (Msg, Def.Size);
end case;
end;
end loop;
for Region in 1 .. Count loop
declare
Region : MAT.Memory.Region_Info;
Kind : ELF.Elf32_Word := 0;
begin
for I in Pos .. Defs'Last loop
declare
Def : MAT.Events.Attribute renames Defs (I);
begin
case Def.Ref is
when M_SIZE =>
Region.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg, Def.Kind);
when M_VADDR =>
Region.Start_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when M_TYPE =>
Kind := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when M_FLAGS =>
Region.Flags := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when others =>
MAT.Readers.Marshaller.Skip (Msg, Def.Size);
end case;
end;
end loop;
if Kind = ELF.PT_LOAD then
Region.Start_Addr := Addr + Region.Start_Addr;
Region.End_Addr := Region.Start_Addr + Region.Size;
Region.Path := Path;
Probe.Target.Process.Memory.Add_Region (Region);
end if;
end;
end loop;
end Probe_Library;
overriding
procedure Extract (Probe : in Process_Probe_Type;
Params : in MAT.Events.Const_Attribute_Table_Access;
Msg : in out MAT.Readers.Message_Type;
Event : in out MAT.Events.Targets.Probe_Event_Type) is
use type MAT.Events.Targets.Probe_Index_Type;
begin
if Event.Index = MSG_BEGIN then
Probe.Probe_Begin (Event.Index, Params.all, Msg);
elsif Event.Index = MSG_LIBRARY then
Probe.Probe_Library (Event.Index, Params.all, Msg);
end if;
end Extract;
procedure Execute (Probe : in Process_Probe_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) is
begin
null;
end Execute;
-- ------------------------------
-- Register the reader to extract and analyze process events.
-- ------------------------------
procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class;
Probe : in Process_Probe_Type_Access) is
begin
Probe.Manager := Into'Unchecked_Access;
Into.Register_Probe (Probe.all'Access, "begin", MSG_BEGIN,
Process_Attributes'Access);
Into.Register_Probe (Probe.all'Access, "end", MSG_END,
Process_Attributes'Access);
Into.Register_Probe (Probe.all'Access, "shlib", MSG_LIBRARY,
Library_Attributes'Access);
end Register;
-- ------------------------------
-- Initialize the target object to prepare for reading process events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is
Process_Probe : constant Process_Probe_Type_Access
:= new Process_Probe_Type;
begin
Process_Probe.Target := Target'Unrestricted_Access;
Process_Probe.Events := Manager.Get_Target_Events;
Register (Manager, Process_Probe);
end Initialize;
end MAT.Targets.Probes;
|
Implement the Probe_Library procedure to collect the information about shared libraries and create a region for each segment used by a shard library Call the Probe_Library when the MSG_LIBRARY event is seen
|
Implement the Probe_Library procedure to collect the information about
shared libraries and create a region for each segment used by a shard library
Call the Probe_Library when the MSG_LIBRARY event is seen
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
599f38c46fc951c64fcf9c87c79dcbb45e5e11cc
|
src/sys/http/aws/aws-client-ext__2.adb
|
src/sys/http/aws/aws-client-ext__2.adb
|
------------------------------------------------------------------------------
-- Ada Web Server --
-- --
-- Copyright (C) 2005-2018, 2020, 2021, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify --
-- it under terms of the GNU General Public License as published by the --
-- Free Software Foundation; either version 3, or (at your option) any --
-- later version. This library is distributed in the hope that it will be --
-- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are --
-- granted additional permissions described in the GCC Runtime Library --
-- Exception, version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
------------------------------------------------------------------------------
pragma Ada_2012;
pragma License (GPL);
with AWS.Messages;
with AWS.Net.Buffered;
with AWS.Translator;
with AWS.Client.HTTP_Utils;
with AWS.Utils;
package body AWS.Client.Ext is
procedure Do_Options
(Connection : in out HTTP_Connection;
Result : out Response.Data;
URI : String := No_Data;
Headers : Header_List := Empty_Header_List) is
begin
Send_Request
(Connection, OPTIONS, Result, URI, No_Content, Headers);
end Do_Options;
function Do_Options
(URL : String;
User : String := No_Data;
Pwd : String := No_Data;
Proxy : String := No_Data;
Proxy_User : String := No_Data;
Proxy_Pwd : String := No_Data;
Timeouts : Timeouts_Values := No_Timeout;
Headers : Header_List := Empty_Header_List;
User_Agent : String := Default.User_Agent) return Response.Data
is
Connection : HTTP_Connection;
Result : Response.Data;
begin
Create (Connection,
URL, User, Pwd, Proxy, Proxy_User, Proxy_Pwd,
Persistent => False,
Timeouts => Timeouts,
User_Agent => User_Agent);
Do_Options (Connection, Result, Headers => Headers);
Close (Connection);
return Result;
exception
when others =>
Close (Connection);
raise;
end Do_Options;
procedure Do_Patch
(Connection : in out HTTP_Connection;
Result : out Response.Data;
URI : String := No_Data;
Data : String;
Headers : Header_List := Empty_Header_List) is
begin
Send_Request
(Connection, PATCH, Result, URI, Translator.To_Stream_Element_Array (Data), Headers);
end Do_Patch;
function Do_Patch
(URL : String;
Data : String;
User : String := No_Data;
Pwd : String := No_Data;
Proxy : String := No_Data;
Proxy_User : String := No_Data;
Proxy_Pwd : String := No_Data;
Timeouts : Timeouts_Values := No_Timeout;
Headers : Header_List := Empty_Header_List;
User_Agent : String := Default.User_Agent) return Response.Data
is
Connection : HTTP_Connection;
Result : Response.Data;
begin
Create (Connection,
URL, User, Pwd, Proxy, Proxy_User, Proxy_Pwd,
Persistent => False,
Timeouts => Timeouts,
User_Agent => User_Agent);
Do_Patch (Connection, Result, Data => Data, Headers => Headers);
Close (Connection);
return Result;
exception
when others =>
Close (Connection);
raise;
end Do_Patch;
function Do_Delete
(URL : String;
Data : String;
User : String := No_Data;
Pwd : String := No_Data;
Proxy : String := No_Data;
Proxy_User : String := No_Data;
Proxy_Pwd : String := No_Data;
Timeouts : Timeouts_Values := No_Timeout;
Headers : Header_List := Empty_Header_List;
User_Agent : String := Default.User_Agent) return Response.Data
is
Connection : HTTP_Connection;
Result : Response.Data;
begin
Create (Connection,
URL, User, Pwd, Proxy, Proxy_User, Proxy_Pwd,
Persistent => False,
Timeouts => Timeouts,
User_Agent => User_Agent);
Do_Delete (Connection, Result, Data, Headers => Headers);
Close (Connection);
return Result;
exception
when others =>
Close (Connection);
raise;
end Do_Delete;
procedure Do_Delete
(Connection : in out HTTP_Connection;
Result : out Response.Data;
Data : String;
URI : String := No_Data;
Headers : Header_List := Empty_Header_List) is
begin
Send_Request
(Connection, DELETE, Result, URI, Translator.To_Stream_Element_Array (Data), Headers);
end Do_Delete;
procedure Send_Header
(Socket : Net.Socket_Type'Class;
Headers : AWS.Headers.List;
End_Block : Boolean := False);
-- Send all header lines in Headers list to the socket
function Get_Line (Headers : AWS.Headers.List; N : Positive) return String;
--------------
-- Get_Line --
--------------
function Get_Line (Headers : AWS.Headers.List; N : Positive) return String is
Pair : constant AWS.Headers.Element := AWS.Headers.Get (Headers, N);
begin
if Pair.Name = "" then
return "";
elsif Pair.Name = Messages.Get_Token
or else Pair.Name = Messages.Post_Token
or else Pair.Name = Messages.Put_Token
or else Pair.Name = Messages.Head_Token
or else Pair.Name = Messages.Delete_Token
or else Pair.Name = Messages.Connect_Token
or else Pair.Name = "OPTIONS"
or else Pair.Name = "PATCH"
or else Pair.Name = HTTP_Version
then
-- And header line
return To_String (Pair.Name & " " & Pair.Value);
else
return To_String (Pair.Name & ": " & Pair.Value);
end if;
end Get_Line;
-----------------
-- Send_Header --
-----------------
procedure Send_Header
(Socket : Net.Socket_Type'Class;
Headers : AWS.Headers.List;
End_Block : Boolean := False) is
begin
for J in 1 .. AWS.Headers.Count (Headers) loop
Net.Buffered.Put_Line (Socket, Get_Line (Headers, J));
end loop;
if End_Block then
Net.Buffered.New_Line (Socket);
Net.Buffered.Flush (Socket);
end if;
end Send_Header;
------------------
-- Send_Request --
------------------
procedure Send_Request
(Connection : in out HTTP_Connection;
Kind : Method_Kind;
Result : out Response.Data;
URI : String;
Data : Stream_Element_Array := No_Content;
Headers : Header_List := Empty_Header_List)
is
use Ada.Real_Time;
Stamp : constant Time := Clock;
Try_Count : Natural := Connection.Retry;
Auth_Attempts : Auth_Attempts_Count := (others => 2);
Auth_Is_Over : Boolean;
begin
Retry : loop
begin
HTTP_Utils.Open_Set_Common_Header
(Connection, Method_Kind'Image (Kind), URI, Headers);
-- If there is some data to send
if Data'Length > 0 then
HTTP_Utils.Set_Header
(Connection.F_Headers,
Messages.Content_Length_Token,
AWS.Utils.Image (Natural (Data'Length)));
end if;
Send_Header
(Connection.Socket.all, Connection.F_Headers, End_Block => True);
-- Send message body
if Data'Length > 0 then
Net.Buffered.Write (Connection.Socket.all, Data);
end if;
HTTP_Utils.Get_Response
(Connection, Result,
Get_Body => Kind /= HEAD and then not Connection.Streaming);
HTTP_Utils.Decrement_Authentication_Attempt
(Connection, Auth_Attempts, Auth_Is_Over);
if Auth_Is_Over then
return;
elsif Kind /= HEAD and then Connection.Streaming then
HTTP_Utils.Read_Body (Connection, Result, Store => False);
end if;
exception
when E : Net.Socket_Error | HTTP_Utils.Connection_Error =>
Error_Processing
(Connection, Try_Count, Result,
Method_Kind'Image (Kind), E, Stamp);
exit Retry when not Response.Is_Empty (Result);
end;
end loop Retry;
end Send_Request;
end AWS.Client.Ext;
|
------------------------------------------------------------------------------
-- Ada Web Server --
-- --
-- Copyright (C) 2005-2018, 2020, 2021, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify --
-- it under terms of the GNU General Public License as published by the --
-- Free Software Foundation; either version 3, or (at your option) any --
-- later version. This library is distributed in the hope that it will be --
-- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are --
-- granted additional permissions described in the GCC Runtime Library --
-- Exception, version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
------------------------------------------------------------------------------
pragma Ada_2012;
pragma License (GPL);
with AWS.Messages;
with AWS.Net.Buffered;
with AWS.Translator;
with AWS.Client.HTTP_Utils;
with AWS.Utils;
package body AWS.Client.Ext is
procedure Do_Options
(Connection : in out HTTP_Connection;
Result : out Response.Data;
URI : String := No_Data;
Headers : Header_List := Empty_Header_List) is
begin
Send_Request
(Connection, OPTIONS, Result, URI, No_Content, Headers);
end Do_Options;
function Do_Options
(URL : String;
User : String := No_Data;
Pwd : String := No_Data;
Proxy : String := No_Data;
Proxy_User : String := No_Data;
Proxy_Pwd : String := No_Data;
Timeouts : Timeouts_Values := No_Timeout;
Headers : Header_List := Empty_Header_List;
User_Agent : String := Default.User_Agent) return Response.Data
is
Connection : HTTP_Connection;
Result : Response.Data;
begin
Create (Connection,
URL, User, Pwd, Proxy, Proxy_User, Proxy_Pwd,
Persistent => False,
Timeouts => Timeouts,
User_Agent => User_Agent);
Do_Options (Connection, Result, Headers => Headers);
Close (Connection);
return Result;
exception
when others =>
Close (Connection);
raise;
end Do_Options;
procedure Do_Patch
(Connection : in out HTTP_Connection;
Result : out Response.Data;
URI : String := No_Data;
Data : String;
Headers : Header_List := Empty_Header_List) is
begin
Send_Request
(Connection, PATCH, Result, URI, Translator.To_Stream_Element_Array (Data), Headers);
end Do_Patch;
function Do_Patch
(URL : String;
Data : String;
User : String := No_Data;
Pwd : String := No_Data;
Proxy : String := No_Data;
Proxy_User : String := No_Data;
Proxy_Pwd : String := No_Data;
Timeouts : Timeouts_Values := No_Timeout;
Headers : Header_List := Empty_Header_List;
User_Agent : String := Default.User_Agent) return Response.Data
is
Connection : HTTP_Connection;
Result : Response.Data;
begin
Create (Connection,
URL, User, Pwd, Proxy, Proxy_User, Proxy_Pwd,
Persistent => False,
Timeouts => Timeouts,
User_Agent => User_Agent);
Do_Patch (Connection, Result, Data => Data, Headers => Headers);
Close (Connection);
return Result;
exception
when others =>
Close (Connection);
raise;
end Do_Patch;
function Do_Delete
(URL : String;
Data : String;
User : String := No_Data;
Pwd : String := No_Data;
Proxy : String := No_Data;
Proxy_User : String := No_Data;
Proxy_Pwd : String := No_Data;
Timeouts : Timeouts_Values := No_Timeout;
Headers : Header_List := Empty_Header_List;
User_Agent : String := Default.User_Agent) return Response.Data
is
Connection : HTTP_Connection;
Result : Response.Data;
begin
Create (Connection,
URL, User, Pwd, Proxy, Proxy_User, Proxy_Pwd,
Persistent => False,
Timeouts => Timeouts,
User_Agent => User_Agent);
Do_Delete (Connection, Result, Data, Headers => Headers);
Close (Connection);
return Result;
exception
when others =>
Close (Connection);
raise;
end Do_Delete;
procedure Do_Delete
(Connection : in out HTTP_Connection;
Result : out Response.Data;
Data : String;
URI : String := No_Data;
Headers : Header_List := Empty_Header_List) is
begin
Send_Request
(Connection, DELETE, Result, URI, Translator.To_Stream_Element_Array (Data), Headers);
end Do_Delete;
procedure Send_Header
(Socket : Net.Socket_Type'Class;
Headers : AWS.Headers.List;
End_Block : Boolean := False);
-- Send all header lines in Headers list to the socket
function Get_Line (Headers : AWS.Headers.List; N : Positive) return String;
--------------
-- Get_Line --
--------------
function Get_Line (Headers : AWS.Headers.List; N : Positive) return String is
Pair : constant AWS.Headers.Element := AWS.Headers.Get (Headers, N);
begin
if Pair.Name = "" then
return "";
elsif Pair.Name = Messages.Get_Token
or else Pair.Name = Messages.Post_Token
or else Pair.Name = Messages.Put_Token
or else Pair.Name = Messages.Head_Token
or else Pair.Name = Messages.Delete_Token
or else Pair.Name = Messages.Connect_Token
or else Pair.Name = "OPTIONS"
or else Pair.Name = "PATCH"
or else Pair.Name = AWS.HTTP_Version
then
-- And header line
return To_String (Pair.Name & " " & Pair.Value);
else
return To_String (Pair.Name & ": " & Pair.Value);
end if;
end Get_Line;
-----------------
-- Send_Header --
-----------------
procedure Send_Header
(Socket : Net.Socket_Type'Class;
Headers : AWS.Headers.List;
End_Block : Boolean := False) is
begin
for J in 1 .. AWS.Headers.Count (Headers) loop
Net.Buffered.Put_Line (Socket, Get_Line (Headers, J));
end loop;
if End_Block then
Net.Buffered.New_Line (Socket);
Net.Buffered.Flush (Socket);
end if;
end Send_Header;
------------------
-- Send_Request --
------------------
procedure Send_Request
(Connection : in out HTTP_Connection;
Kind : Method_Kind;
Result : out Response.Data;
URI : String;
Data : Stream_Element_Array := No_Content;
Headers : Header_List := Empty_Header_List)
is
use Ada.Real_Time;
Stamp : constant Time := Clock;
Try_Count : Natural := Connection.Retry;
Auth_Attempts : Auth_Attempts_Count := (others => 2);
Auth_Is_Over : Boolean;
begin
Retry : loop
begin
HTTP_Utils.Open_Set_Common_Header
(Connection, Method_Kind'Image (Kind), URI, Headers);
-- If there is some data to send
if Data'Length > 0 then
HTTP_Utils.Set_Header
(Connection.F_Headers,
Messages.Content_Length_Token,
AWS.Utils.Image (Natural (Data'Length)));
end if;
Send_Header
(Connection.Socket.all, Connection.F_Headers, End_Block => True);
-- Send message body
if Data'Length > 0 then
Net.Buffered.Write (Connection.Socket.all, Data);
end if;
HTTP_Utils.Get_Response
(Connection, Result,
Get_Body => Kind /= HEAD and then not Connection.Streaming);
HTTP_Utils.Decrement_Authentication_Attempt
(Connection, Auth_Attempts, Auth_Is_Over);
if Auth_Is_Over then
return;
elsif Kind /= HEAD and then Connection.Streaming then
HTTP_Utils.Read_Body (Connection, Result, Store => False);
end if;
exception
when E : Net.Socket_Error | HTTP_Utils.Connection_Error =>
Error_Processing
(Connection, Try_Count, Result,
Method_Kind'Image (Kind), E, Stamp);
exit Retry when not Response.Is_Empty (Result);
end;
end loop Retry;
end Send_Request;
end AWS.Client.Ext;
|
Fix compilation with AWS git
|
Fix compilation with AWS git
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e5aab30165a56a091601d75ee624a60b675d42e3
|
src/sys/streams/util-streams-texts.adb
|
src/sys/streams/util-streams-texts.adb
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
package body Util.Streams.Texts is
use Ada.Streams;
subtype Offset is Ada.Streams.Stream_Element_Offset;
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access) is
begin
Stream.Initialize (Output => To, Size => 4096);
end Initialize;
-- ------------------------------
-- Write a raw character on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Char : in Character) is
Buf : constant Ada.Streams.Stream_Element_Array (1 .. 1)
:= (1 => Ada.Streams.Stream_Element (Character'Pos (Char)));
begin
Stream.Write (Buf);
end Write;
-- ------------------------------
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
-- ------------------------------
procedure Write_Wide (Stream : in out Print_Stream;
Item : in Wide_Wide_Character) is
use Interfaces;
Val : Unsigned_32;
Buf : Ada.Streams.Stream_Element_Array (1 .. 4);
begin
-- UTF-8 conversion
-- 7 U+0000 U+007F 1 0xxxxxxx
-- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx
-- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx
-- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Val := Wide_Wide_Character'Pos (Item);
if Val <= 16#7f# then
Buf (1) := Ada.Streams.Stream_Element (Val);
Stream.Write (Buf (1 .. 1));
elsif Val <= 16#07FF# then
Buf (1) := Stream_Element (16#C0# or Shift_Right (Val, 6));
Buf (2) := Stream_Element (16#80# or (Val and 16#03F#));
Stream.Write (Buf (1 .. 2));
elsif Val <= 16#0FFFF# then
Buf (1) := Stream_Element (16#E0# or Shift_Right (Val, 12));
Val := Val and 16#0FFF#;
Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 6));
Buf (3) := Stream_Element (16#80# or (Val and 16#03F#));
Stream.Write (Buf (1 .. 3));
else
Val := Val and 16#1FFFFF#;
Buf (1) := Stream_Element (16#F0# or Shift_Right (Val, 18));
Val := Val and 16#3FFFF#;
Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 12));
Val := Val and 16#0FFF#;
Buf (3) := Stream_Element (16#80# or Shift_Right (Val, 6));
Buf (4) := Stream_Element (16#80# or (Val and 16#03F#));
Stream.Write (Buf (1 .. 4));
end if;
end Write_Wide;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in String) is
Buf : Ada.Streams.Stream_Element_Array (Offset (Item'First) .. Offset (Item'Last));
for Buf'Address use Item'Address;
begin
Stream.Write (Buf);
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String) is
Count : constant Natural := Ada.Strings.Unbounded.Length (Item);
begin
if Count > 0 then
for I in 1 .. Count loop
Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I));
end loop;
end if;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is
Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item);
C : Wide_Wide_Character;
begin
if Count > 0 then
for I in 1 .. Count loop
C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I);
Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C)));
end loop;
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Integer) is
S : constant String := Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer) is
S : constant String := Long_Long_Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write a date on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date) is
begin
Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format));
end Write;
-- ------------------------------
-- Get the output stream content as a string.
-- ------------------------------
function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is
Size : constant Natural := Stream.Get_Size;
Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer;
Result : String (1 .. Size);
begin
for I in Result'Range loop
Result (I) := Character'Val (Buffer (Stream_Element_Offset (I)));
end loop;
return Result;
end To_String;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character) is
begin
Stream.Write (Item);
end Write_Char;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character) is
begin
Stream.Write_Wide (Item);
end Write_Char;
-- ------------------------------
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
-- ------------------------------
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access) is
begin
Stream.Initialize (Input => From, Size => 4096);
end Initialize;
-- ------------------------------
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
-- ------------------------------
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False) is
C : Character;
begin
while not Stream.Is_Eof loop
Stream.Read (C);
if C = ASCII.LF then
if not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
return;
elsif C /= ASCII.CR or not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
return;
end Read_Line;
end Util.Streams.Texts;
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
package body Util.Streams.Texts is
use Ada.Streams;
subtype Offset is Ada.Streams.Stream_Element_Offset;
procedure Initialize (Stream : in out Print_Stream;
To : access Output_Stream'Class) is
begin
Stream.Initialize (Output => To, Size => 4096);
end Initialize;
-- ------------------------------
-- Write a raw character on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Char : in Character) is
Buf : constant Ada.Streams.Stream_Element_Array (1 .. 1)
:= (1 => Ada.Streams.Stream_Element (Character'Pos (Char)));
begin
Stream.Write (Buf);
end Write;
-- ------------------------------
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
-- ------------------------------
procedure Write_Wide (Stream : in out Print_Stream;
Item : in Wide_Wide_Character) is
use Interfaces;
Val : Unsigned_32;
Buf : Ada.Streams.Stream_Element_Array (1 .. 4);
begin
-- UTF-8 conversion
-- 7 U+0000 U+007F 1 0xxxxxxx
-- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx
-- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx
-- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Val := Wide_Wide_Character'Pos (Item);
if Val <= 16#7f# then
Buf (1) := Ada.Streams.Stream_Element (Val);
Stream.Write (Buf (1 .. 1));
elsif Val <= 16#07FF# then
Buf (1) := Stream_Element (16#C0# or Shift_Right (Val, 6));
Buf (2) := Stream_Element (16#80# or (Val and 16#03F#));
Stream.Write (Buf (1 .. 2));
elsif Val <= 16#0FFFF# then
Buf (1) := Stream_Element (16#E0# or Shift_Right (Val, 12));
Val := Val and 16#0FFF#;
Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 6));
Buf (3) := Stream_Element (16#80# or (Val and 16#03F#));
Stream.Write (Buf (1 .. 3));
else
Val := Val and 16#1FFFFF#;
Buf (1) := Stream_Element (16#F0# or Shift_Right (Val, 18));
Val := Val and 16#3FFFF#;
Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 12));
Val := Val and 16#0FFF#;
Buf (3) := Stream_Element (16#80# or Shift_Right (Val, 6));
Buf (4) := Stream_Element (16#80# or (Val and 16#03F#));
Stream.Write (Buf (1 .. 4));
end if;
end Write_Wide;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in String) is
Buf : Ada.Streams.Stream_Element_Array (Offset (Item'First) .. Offset (Item'Last));
for Buf'Address use Item'Address;
begin
Stream.Write (Buf);
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String) is
Count : constant Natural := Ada.Strings.Unbounded.Length (Item);
begin
if Count > 0 then
for I in 1 .. Count loop
Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I));
end loop;
end if;
end Write;
-- ------------------------------
-- Write a raw string on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is
Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item);
C : Wide_Wide_Character;
begin
if Count > 0 then
for I in 1 .. Count loop
C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I);
Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C)));
end loop;
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Integer) is
S : constant String := Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write an integer on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer) is
S : constant String := Long_Long_Integer'Image (Item);
begin
if Item > 0 then
Stream.Write (S (S'First + 1 .. S'Last));
else
Stream.Write (S);
end if;
end Write;
-- ------------------------------
-- Write a date on the stream.
-- ------------------------------
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date) is
begin
Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format));
end Write;
-- ------------------------------
-- Get the output stream content as a string.
-- ------------------------------
function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is
Size : constant Natural := Stream.Get_Size;
Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer;
Result : String (1 .. Size);
begin
for I in Result'Range loop
Result (I) := Character'Val (Buffer (Stream_Element_Offset (I)));
end loop;
return Result;
end To_String;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character) is
begin
Stream.Write (Item);
end Write_Char;
-- ------------------------------
-- Write a character on the stream.
-- ------------------------------
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character) is
begin
Stream.Write_Wide (Item);
end Write_Char;
-- ------------------------------
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
-- ------------------------------
procedure Initialize (Stream : in out Reader_Stream;
From : access Input_Stream'Class) is
begin
Stream.Initialize (Input => From, Size => 4096);
end Initialize;
-- ------------------------------
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
-- ------------------------------
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False) is
C : Character;
begin
while not Stream.Is_Eof loop
Stream.Read (C);
if C = ASCII.LF then
if not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
return;
elsif C /= ASCII.CR or not Strip then
Ada.Strings.Unbounded.Append (Into, C);
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
return;
end Read_Line;
end Util.Streams.Texts;
|
Use anonymous access type for the input and output streams
|
Use anonymous access type for the input and output streams
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b05718970f399a787a844582f21d0b9ca5a17bd6
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Utils;
with ADO.Sessions;
with ADO.Sessions.Entities;
with Util.Beans.Lists.Strings;
with AWA.Tags.Modules;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "tags" then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Service.Load_Question (From, Id);
From.Tags.Load_Tags (DB, Id);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
Bean.Tags.Update_Tags (Bean.Get_Id);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE);
Object.Tags.Set_Permission ("question-edit");
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Utils.To_Identifier (Value));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Utils.To_Identifier (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Answer (Answer => Bean);
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
Pos : Natural;
begin
if Name = "tags" then
Pos := From.Questions.Get_Row_Index;
if Pos = 0 then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Models.Question_Info := From.Questions.List.Element (Pos);
begin
return From.Tags.Get_Tags (Item.Id);
end;
elsif Name = "questions" then
return Util.Beans.Objects.To_Object (Value => From.Questions_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return From.Questions.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "tag" then
From.Tag := Util.Beans.Objects.To_Unbounded_String (Value);
From.Load_List;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of question. If a tag was set, filter the list of questions with the tag.
-- ------------------------------
procedure Load_List (Into : in out Question_List_Bean) is
use AWA.Questions.Models;
use AWA.Services;
use type ADO.Identifier;
Session : ADO.Sessions.Session := Into.Service.Get_Session;
Query : ADO.Queries.Context;
Tag_Id : ADO.Identifier;
begin
AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id);
if Tag_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List);
Query.Bind_Param (Name => "tag", Value => Tag_Id);
else
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
end if;
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Into.Questions, Session, Query);
declare
List : ADO.Utils.Identifier_Vector;
Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First;
begin
while Question_Info_Vectors.Has_Element (Iter) loop
List.Append (Question_Info_Vectors.Element (Iter).Id);
Question_Info_Vectors.Next (Iter);
end loop;
Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all,
List);
end;
end Load_List;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_List_Bean_Access := new Question_List_Bean;
-- Session : ADO.Sessions.Session := Module.Get_Session;
-- Query : ADO.Queries.Context;
begin
Object.Service := Module;
Object.Questions_Bean := Object.Questions'Unchecked_Access;
-- Query.Set_Query (AWA.Questions.Models.Query_Question_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "entity_type",
-- Table => AWA.Questions.Models.QUESTION_TABLE,
-- Session => Session);
-- AWA.Questions.Models.List (Object.Questions, Session, Query);
Object.Load_List;
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "tags" then
return Util.Beans.Objects.To_Object (Value => From.Tags_Bean,
Storage => Util.Beans.Objects.STATIC);
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 Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Id);
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
-- Load the tags if any.
From.Tags.Load_Tags (Session, Id);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE);
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Utils;
with ADO.Sessions;
with ADO.Sessions.Entities;
with Util.Beans.Lists.Strings;
with AWA.Tags.Modules;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "tags" then
return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC);
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Question_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "title" then
From.Set_Title (Util.Beans.Objects.To_String (Value));
elsif Name = "description" then
From.Set_Description (Util.Beans.Objects.To_String (Value));
elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
From.Service.Load_Question (From, Id);
From.Tags.Load_Tags (DB, Id);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Question (Bean);
Bean.Tags.Update_Tags (Bean.Get_Id);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Question (Bean);
end Delete;
-- ------------------------------
-- Create the Question_Bean bean instance.
-- ------------------------------
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Bean_Access := new Question_Bean;
begin
Object.Service := Module;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE);
Object.Tags.Set_Permission ("question-edit");
return Object.all'Access;
end Create_Question_Bean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "question_id" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id));
elsif From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
From.Service.Load_Answer (From, From.Question,
ADO.Utils.To_Identifier (Value));
elsif Name = "answer" then
From.Set_Answer (Util.Beans.Objects.To_String (Value));
elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then
From.Service.Load_Question (From.Question,
ADO.Utils.To_Identifier (Value));
end if;
end Set_Value;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Save_Answer (Question => Bean.Question,
Answer => Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Service.Delete_Answer (Answer => Bean);
end Delete;
-- ------------------------------
-- Create the answer bean instance.
-- ------------------------------
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Answer_Bean_Access := new Answer_Bean;
begin
Object.Service := Module;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
Pos : Natural;
begin
if Name = "tags" then
Pos := From.Questions.Get_Row_Index;
if Pos = 0 then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Models.Question_Info := From.Questions.List.Element (Pos - 1);
begin
return From.Tags.Get_Tags (Item.Id);
end;
elsif Name = "questions" then
return Util.Beans.Objects.To_Object (Value => From.Questions_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return From.Questions.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Question_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "tag" then
From.Tag := Util.Beans.Objects.To_Unbounded_String (Value);
From.Load_List;
end if;
end Set_Value;
-- ------------------------------
-- Load the list of question. If a tag was set, filter the list of questions with the tag.
-- ------------------------------
procedure Load_List (Into : in out Question_List_Bean) is
use AWA.Questions.Models;
use AWA.Services;
use type ADO.Identifier;
Session : ADO.Sessions.Session := Into.Service.Get_Session;
Query : ADO.Queries.Context;
Tag_Id : ADO.Identifier;
begin
AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id);
if Tag_Id /= ADO.NO_IDENTIFIER then
Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List);
Query.Bind_Param (Name => "tag", Value => Tag_Id);
else
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
end if;
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Into.Questions, Session, Query);
declare
List : ADO.Utils.Identifier_Vector;
Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First;
begin
while Question_Info_Vectors.Has_Element (Iter) loop
List.Append (Question_Info_Vectors.Element (Iter).Id);
Question_Info_Vectors.Next (Iter);
end loop;
Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all,
List);
end;
end Load_List;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_List_Bean_Access := new Question_List_Bean;
-- Session : ADO.Sessions.Session := Module.Get_Session;
-- Query : ADO.Queries.Context;
begin
Object.Service := Module;
Object.Questions_Bean := Object.Questions'Unchecked_Access;
-- Query.Set_Query (AWA.Questions.Models.Query_Question_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "entity_type",
-- Table => AWA.Questions.Models.QUESTION_TABLE,
-- Session => Session);
-- AWA.Questions.Models.List (Object.Questions, Session, Query);
Object.Load_List;
return Object.all'Access;
end Create_Question_List_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "answers" then
return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "question" then
return Util.Beans.Objects.To_Object (Value => From.Question_Bean,
Storage => Util.Beans.Objects.STATIC);
elsif Name = "tags" then
return Util.Beans.Objects.To_Object (Value => From.Tags_Bean,
Storage => Util.Beans.Objects.STATIC);
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 Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
declare
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Id);
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.ANSWER_TABLE,
Session => Session);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (From.Answer_List, Session, Query);
-- Load the tags if any.
From.Tags.Load_Tags (Session, Id);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the Question_Display_Bean bean instance.
-- ------------------------------
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Question_Display_Bean_Access := new Question_Display_Bean;
begin
Object.Service := Module;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
Object.Tags_Bean := Object.Tags'Access;
Object.Tags.Set_Entity_Type (AWA.Questions.Models.QUESTION_TABLE);
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Fix getting the current question identifier
|
Fix getting the current question identifier
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
c967bb150834e99fe4c9ed8ddfd48e738f3389b5
|
src/asf-contexts-writer.ads
|
src/asf-contexts-writer.ads
|
-----------------------------------------------------------------------
-- writer -- Response stream 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.
-----------------------------------------------------------------------
-- The <b>ASF.Contexts.Writer</b> defines the response writer to
-- write the rendered result to the response stream. The <b>IOWriter</b>
-- interface defines the procedure for writing the buffer to the output
-- stream. The <b>Response_Writer</b> is the main type that provides
-- various methods for writing the content.
--
-- The result stream is encoded according to the encoding type.
--
with Unicode.Encodings;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with EL.Objects;
with Util.Beans.Objects;
with ASF.Streams;
package ASF.Contexts.Writer is
use Ada.Strings.Unbounded;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- IO Writer
-- ------------------------------
type IOWriter is limited interface;
procedure Write (Stream : in out IOWriter;
Buffer : in Ada.Streams.Stream_Element_Array) is abstract;
-- ------------------------------
-- Response Writer
-- ------------------------------
type Response_Writer is new ASF.Streams.Print_Stream with private;
type Response_Writer_Access is access all Response_Writer'Class;
-- Backward compatibility
subtype ResponseWriter is Response_Writer;
pragma Obsolescent (Entity => ResponseWriter);
subtype ResponseWriter_Access is Response_Writer_Access;
pragma Obsolescent (Entity => ResponseWriter_Access);
-- Initialize the response stream for the given content type and
-- encoding. An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Response_Writer;
Content_Type : in String;
Encoding : in String;
Output : in ASF.Streams.Print_Stream);
-- Get the content type.
function Get_Content_Type (Stream : in Response_Writer) return String;
-- Get the character encoding.
function Get_Encoding (Stream : in Response_Writer) return String;
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Response_Writer'Class);
-- Start an XML element with the given name.
procedure Start_Element (Stream : in out Response_Writer;
Name : in String);
-- Start an optional XML element with the given name.
-- The element is written only if it has at least one attribute.
-- The optional XML element must not contain other XML entities.
procedure Start_Optional_Element (Stream : in out Response_Writer;
Name : in String);
-- Closes an XML element of the given name.
procedure End_Element (Stream : in out Response_Writer;
Name : in String);
-- Closes an optional XML element of the given name.
-- The ending tag is written only if the start tag was written.
procedure End_Optional_Element (Stream : in out Response_Writer;
Name : in String);
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
procedure Write_Element (Stream : in out Response_Writer;
Name : in String;
Content : in String);
procedure Write_Wide_Element (Stream : in out Response_Writer;
Name : in String;
Content : in Wide_Wide_String);
procedure Write_Wide_Element (Stream : in out Response_Writer;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in String);
procedure Write_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in Unbounded_String);
procedure Write_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in EL.Objects.Object);
procedure Write_Wide_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in Wide_Wide_String);
procedure Write_Wide_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in Unbounded_Wide_Wide_String);
-- Write a text escaping any character as necessary.
procedure Write_Text (Stream : in out Response_Writer;
Text : in String);
procedure Write_Text (Stream : in out Response_Writer;
Text : in Unbounded_String);
procedure Write_Wide_Text (Stream : in out Response_Writer;
Text : in Wide_Wide_String);
procedure Write_Wide_Text (Stream : in out Response_Writer;
Text : in Unbounded_Wide_Wide_String);
procedure Write_Text (Stream : in out Response_Writer;
Value : in EL.Objects.Object);
-- Write a character on the response stream and escape that character
-- as necessary.
procedure Write_Char (Stream : in out Response_Writer;
Char : in Character);
-- Write a character on the response stream and escape that character
-- as necessary.
procedure Write_Wide_Char (Stream : in out Response_Writer;
Char : in Wide_Wide_Character);
-- Write a string on the stream.
procedure Write (Stream : in out Response_Writer;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write_Raw (Stream : in out Response_Writer;
Item : in String);
-- Write a raw wide string on the stream.
procedure Write_Wide_Raw (Stream : in out Response_Writer;
Item : in Wide_Wide_String);
-- ------------------------------
-- Javascript Support
-- ------------------------------
-- To optimize the execution of Javascript page code, ASF components can queue some
-- javascript code and have it merged and executed in a single <script> command.
-- Write the java scripts that have been queued by <b>Queue_Script</b>
procedure Write_Scripts (Stream : in out Response_Writer);
-- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped.
procedure Queue_Script (Stream : in out Response_Writer;
Script : in String);
-- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped.
procedure Queue_Script (Stream : in out Response_Writer;
Script : in Ada.Strings.Unbounded.Unbounded_String);
-- Append the <b>Value</b> to the javascript buffer queue. The value is escaped according
-- to Javascript escape rules.
procedure Queue_Script (Stream : in out Response_Writer;
Value : in Util.Beans.Objects.Object);
-- Flush the response.
-- Before flusing the response, the javascript are also flushed
-- by calling <b>Write_Scripts</b>.
overriding
procedure Flush (Stream : in out Response_Writer);
private
use Ada.Streams;
-- Flush the response stream and release the buffer.
overriding
procedure Finalize (Object : in out Response_Writer);
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
type Response_Writer is new ASF.Streams.Print_Stream with record
-- Whether an XML element must be closed (that is a '>' is necessary)
Close_Start : Boolean := False;
-- The encoding scheme.
Encoding : Unicode.Encodings.Unicode_Encoding;
-- The content type.
Content_Type : Unbounded_String;
-- The javascript that has been queued by <b>Queue_Script</b>.
Script_Queue : Unbounded_String;
-- An optional element to write in the stream.
Optional_Element : String (1 .. 32);
Optional_Element_Size : Natural := 0;
Optional_Element_Written : Boolean := False;
end record;
end ASF.Contexts.Writer;
|
-----------------------------------------------------------------------
-- writer -- Response stream 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.
-----------------------------------------------------------------------
-- The <b>ASF.Contexts.Writer</b> defines the response writer to
-- write the rendered result to the response stream. The <b>IOWriter</b>
-- interface defines the procedure for writing the buffer to the output
-- stream. The <b>Response_Writer</b> is the main type that provides
-- various methods for writing the content.
--
-- The result stream is encoded according to the encoding type.
--
with Unicode.Encodings;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with EL.Objects;
with Util.Beans.Objects;
with ASF.Streams;
package ASF.Contexts.Writer is
use Ada.Strings.Unbounded;
use Ada.Strings.Wide_Wide_Unbounded;
-- ------------------------------
-- IO Writer
-- ------------------------------
type IOWriter is limited interface;
procedure Write (Stream : in out IOWriter;
Buffer : in Ada.Streams.Stream_Element_Array) is abstract;
-- ------------------------------
-- Response Writer
-- ------------------------------
type Response_Writer is new ASF.Streams.Print_Stream with private;
type Response_Writer_Access is access all Response_Writer'Class;
-- Backward compatibility
subtype ResponseWriter is Response_Writer;
pragma Obsolescent (Entity => ResponseWriter);
subtype ResponseWriter_Access is Response_Writer_Access;
pragma Obsolescent (Entity => ResponseWriter_Access);
-- Initialize the response stream for the given content type and
-- encoding. An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Response_Writer;
Content_Type : in String;
Encoding : in String;
Output : in ASF.Streams.Print_Stream);
-- Get the content type.
function Get_Content_Type (Stream : in Response_Writer) return String;
-- Get the character encoding.
function Get_Encoding (Stream : in Response_Writer) return String;
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Response_Writer'Class);
-- Start an XML element with the given name.
procedure Start_Element (Stream : in out Response_Writer;
Name : in String);
-- Start an optional XML element with the given name.
-- The element is written only if it has at least one attribute.
-- The optional XML element must not contain other XML entities.
procedure Start_Optional_Element (Stream : in out Response_Writer;
Name : in String);
-- Closes an XML element of the given name.
procedure End_Element (Stream : in out Response_Writer;
Name : in String);
-- Closes an optional XML element of the given name.
-- The ending tag is written only if the start tag was written.
procedure End_Optional_Element (Stream : in out Response_Writer;
Name : in String);
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
procedure Write_Element (Stream : in out Response_Writer;
Name : in String;
Content : in String);
procedure Write_Wide_Element (Stream : in out Response_Writer;
Name : in String;
Content : in Wide_Wide_String);
procedure Write_Wide_Element (Stream : in out Response_Writer;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in String);
procedure Write_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in Unbounded_String);
procedure Write_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in EL.Objects.Object);
procedure Write_Wide_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in Wide_Wide_String);
procedure Write_Wide_Attribute (Stream : in out Response_Writer;
Name : in String;
Value : in Unbounded_Wide_Wide_String);
-- Write a text escaping any character as necessary.
procedure Write_Text (Stream : in out Response_Writer;
Text : in String);
procedure Write_Text (Stream : in out Response_Writer;
Text : in Unbounded_String);
procedure Write_Wide_Text (Stream : in out Response_Writer;
Text : in Wide_Wide_String);
procedure Write_Wide_Text (Stream : in out Response_Writer;
Text : in Unbounded_Wide_Wide_String);
procedure Write_Text (Stream : in out Response_Writer;
Value : in EL.Objects.Object);
-- Write a character on the response stream and escape that character
-- as necessary.
procedure Write_Char (Stream : in out Response_Writer;
Char : in Character);
-- Write a character on the response stream and escape that character
-- as necessary.
procedure Write_Wide_Char (Stream : in out Response_Writer;
Char : in Wide_Wide_Character);
-- Write a string on the stream.
procedure Write (Stream : in out Response_Writer;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write_Raw (Stream : in out Response_Writer;
Item : in String);
-- Write a raw wide string on the stream.
procedure Write_Raw (Stream : in out Response_Writer;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write a raw wide string on the stream.
procedure Write_Wide_Raw (Stream : in out Response_Writer;
Item : in Wide_Wide_String);
-- ------------------------------
-- Javascript Support
-- ------------------------------
-- To optimize the execution of Javascript page code, ASF components can queue some
-- javascript code and have it merged and executed in a single <script> command.
-- Write the java scripts that have been queued by <b>Queue_Script</b>
procedure Write_Scripts (Stream : in out Response_Writer);
-- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped.
procedure Queue_Script (Stream : in out Response_Writer;
Script : in String);
-- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped.
procedure Queue_Script (Stream : in out Response_Writer;
Script : in Ada.Strings.Unbounded.Unbounded_String);
-- Append the <b>Value</b> to the javascript buffer queue. The value is escaped according
-- to Javascript escape rules.
procedure Queue_Script (Stream : in out Response_Writer;
Value : in Util.Beans.Objects.Object);
-- Flush the response.
-- Before flusing the response, the javascript are also flushed
-- by calling <b>Write_Scripts</b>.
overriding
procedure Flush (Stream : in out Response_Writer);
private
use Ada.Streams;
-- Flush the response stream and release the buffer.
overriding
procedure Finalize (Object : in out Response_Writer);
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
type Response_Writer is new ASF.Streams.Print_Stream with record
-- Whether an XML element must be closed (that is a '>' is necessary)
Close_Start : Boolean := False;
-- The encoding scheme.
Encoding : Unicode.Encodings.Unicode_Encoding;
-- The content type.
Content_Type : Unbounded_String;
-- The javascript that has been queued by <b>Queue_Script</b>.
Script_Queue : Unbounded_String;
-- An optional element to write in the stream.
Optional_Element : String (1 .. 32);
Optional_Element_Size : Natural := 0;
Optional_Element_Written : Boolean := False;
end record;
end ASF.Contexts.Writer;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
7d9e3fa1896d384c6fdc667711343fe87d08b613
|
src/babel-strategies-workers.ads
|
src/babel-strategies-workers.ads
|
-----------------------------------------------------------------------
-- babel-strategies-workers -- Tasks that perform strategy work
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Babel.Strategies.Workers is
type Worker_Type (Count : Positive) is limited private;
procedure Start (Worker : in out Worker_Type;
Strategy : in Babel.Strategies.Strategy_Type_Access);
private
task type Worker_Task is
entry Start (Strategy : in Babel.Strategies.Strategy_Type_Access);
end Worker_Task;
type Worker_Task_Array is array (Positive range <>) of Worker_Task;
type Worker_Type (Count : Positive) is limited record
Workers : Worker_Task_Array (1 .. Count);
end record;
end Babel.Strategies.Workers;
|
-----------------------------------------------------------------------
-- babel-strategies-workers -- Tasks that perform strategy work
-- 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.
-----------------------------------------------------------------------
generic
type Worker_Strategy is limited new Babel.Strategies.Strategy_Type with private;
package Babel.Strategies.Workers is
type Worker_Type (Count : Positive) is limited private;
procedure Configure (Worker : in out Worker_Type;
Process : not null access procedure (S : in out Worker_Strategy));
procedure Start (Worker : in out Worker_Type);
procedure Finish (Worker : in out Worker_Type;
Database : in out Babel.Base.Database'Class);
private
task type Worker_Task is
entry Start (Strategy : in Babel.Strategies.Strategy_Type_Access);
entry Finish (Database : in out Babel.Base.Database'Class);
end Worker_Task;
type Worker_Task_Array is array (Positive range <>) of Worker_Task;
type Strategy_Array is array (Positive range <>) of aliased Worker_Strategy;
type Worker_Type (Count : Positive) is limited record
Workers : Worker_Task_Array (1 .. Count);
Strategies : Strategy_Array (1 .. Count);
end record;
end Babel.Strategies.Workers;
|
Change to a generic package and define a table of strategy objects Declare the Configure procedure
|
Change to a generic package and define a table of strategy objects
Declare the Configure procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
499febb37102f8d68e78ce5b296e2dbb752716c6
|
awa/src/awa-commands-info.adb
|
awa/src/awa-commands-info.adb
|
-----------------------------------------------------------------------
-- akt-commands-info -- Info command to describe the current configuration
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Commands.Info is
use type AWA.Modules.Module_Access;
-- ------------------------------
-- Print the configuration identified by the given name.
-- ------------------------------
procedure Print (Command : in out Command_Type;
Name : in String;
Value : in String;
Default : in String;
Context : in out Context_Type) is
pragma Unreferenced (Default);
Pos : Natural;
begin
Context.Console.Start_Row;
Context.Console.Print_Field (1, Name);
Pos := Value'First;
while Pos <= Value'Last loop
if Value'Last - Pos > Command.Value_Length then
Context.Console.Print_Field (2, Value (Pos .. Pos + Command.Value_Length - 1));
Pos := Pos + Command.Value_Length;
Context.Console.End_Row;
Context.Console.Start_Row;
Context.Console.Print_Field (1, "");
else
Context.Console.Print_Field (2, Value (Pos .. Value'Last));
Pos := Pos + Value'Length;
end if;
end loop;
Context.Console.End_Row;
end Print;
procedure Print (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Application.Get_Init_Parameter (Name, Default);
begin
Command.Print (Name, Value, Default, Context);
end Print;
procedure Print (Command : in out Command_Type;
Module : in AWA.Modules.Module'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Module.Get_Config (Name, Default);
begin
Command.Print (Module.Get_Name & "." & Name, Value, Default, Context);
end Print;
-- ------------------------------
-- Print the configuration about the application.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Args);
Module : AWA.Modules.Module_Access;
begin
if Command.Long_List then
Command.Value_Length := Natural'Last;
end if;
Application.Load_Bundle (Name => "commands",
Locale => "en",
Bundle => Command.Bundle);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Database configuration");
Context.Console.Notice (N_INFO, "----------------------");
Command.Print (Application, "database", "", Context);
Command.Print (Application, "ado.queries.paths", "", Context);
Command.Print (Application, "ado.queries.load", "", Context);
Command.Print (Application, "ado.drivers.load", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Server faces configuration");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "view.dir",
ASF.Applications.DEF_VIEW_DIR, Context);
Command.Print (Application, "view.escape_unknown_tags",
ASF.Applications.DEF_ESCAPE_UNKNOWN_TAGS, Context);
Command.Print (Application, "view.ext",
ASF.Applications.DEF_VIEW_EXT, Context);
Command.Print (Application, "view.file_ext",
ASF.Applications.DEF_VIEW_FILE_EXT, Context);
Command.Print (Application, "view.ignore_spaces",
ASF.Applications.DEF_IGNORE_WHITE_SPACES, Context);
Command.Print (Application, "view.ignore_empty_lines",
ASF.Applications.DEF_IGNORE_EMPTY_LINES, Context);
Command.Print (Application, "view.static.dir",
ASF.Applications.DEF_STATIC_DIR, Context);
Command.Print (Application, "bundle.dir", "bundles", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "AWA Application");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "app_name", "", Context);
Command.Print (Application, "app_search_dirs", ".", Context);
Command.Print (Application, "app.modules.dir", "", Context);
Command.Print (Application, "app_url_base", "", Context);
Command.Print (Application, "awa_url_base", "", Context);
Command.Print (Application, "awa_url_host", "", Context);
Command.Print (Application, "awa_url_port", "", Context);
Command.Print (Application, "awa_url_scheme", "", Context);
Command.Print (Application, "app.config", "awa.xml", Context);
Command.Print (Application, "app.config.plugins", "", Context);
Command.Print (Application, "contextPath", "", Context);
Command.Print (Application, "awa_dispatcher_count", "", Context);
Command.Print (Application, "awa_dispatcher_priority", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Users Module");
Context.Console.Notice (N_INFO, "------------");
Command.Print (Application, "openid.realm", "", Context);
Command.Print (Application, "openid.callback_url", "", Context);
Command.Print (Application, "openid.success_url", "", Context);
Command.Print (Application, "auth.url.orange", "", Context);
Command.Print (Application, "auth.provider.oranger", "", Context);
Command.Print (Application, "auth.url.yahoo", "", Context);
Command.Print (Application, "auth.provider.yahoo", "", Context);
Command.Print (Application, "auth.url.google", "", Context);
Command.Print (Application, "auth.provider.google", "", Context);
Command.Print (Application, "auth.url.facebook", "", Context);
Command.Print (Application, "auth.provider.facebook", "", Context);
Command.Print (Application, "auth.url.google-plus", "", Context);
Command.Print (Application, "auth.provider.google-plus", "", Context);
Command.Print (Application, "facebook.callback_url", "", Context);
Command.Print (Application, "facebook.request_url", "", Context);
Command.Print (Application, "facebook.scope", "", Context);
Command.Print (Application, "facebook.client_id", "", Context);
Command.Print (Application, "facebook.secret", "", Context);
Command.Print (Application, "google-plus.issuer", "", Context);
Command.Print (Application, "google-plus.callback_url", "", Context);
Command.Print (Application, "google-plus.request_url", "", Context);
Command.Print (Application, "google-plus.scope", "", Context);
Command.Print (Application, "google-plus.client_id", "", Context);
Command.Print (Application, "google-plus.secret", "", Context);
Command.Print (Application, "auth-filter.redirect", "", Context);
Command.Print (Application, "verify-filter.redirect", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Mail Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Application, "mail.smtp.host", "", Context);
Command.Print (Application, "mail.smtp.port", "", Context);
Command.Print (Application, "mail.smtp.enable", "true", Context);
Command.Print (Application, "mail.mailer", "smtp", Context);
Command.Print (Application, "mail.file.maildir", "mail", Context);
Command.Print (Application, "app_mail_name", "", Context);
Command.Print (Application, "app_mail_from", "", Context);
Module := Application.Find_Module ("workspaces");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Workspace Module");
Context.Console.Notice (N_INFO, "----------------");
Command.Print (Module.all, "permissions_list", "", Context);
Command.Print (Module.all, "allow_workspace_create", "", Context);
end if;
Module := Application.Find_Module ("storages");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Storage Module");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Module.all, "database_max_size", "100000", Context);
Command.Print (Module.all, "storage_root", "storage", Context);
Command.Print (Module.all, "tmp_storage_root", "tmp", Context);
Module := Application.Find_Module ("images");
if Module /= null then
Command.Print (Module.all, "thumbnail_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("wikis");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Wiki Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Module.all, "image_prefix", "", Context);
Command.Print (Module.all, "page_prefix", "", Context);
Command.Print (Module.all, "wiki_copy_list", "", Context);
Module := Application.Find_Module ("wiki_previews");
if Module /= null then
Command.Print (Module.all, "wiki_preview_tmp", "tmp", Context);
Command.Print (Module.all, "wiki_preview_dir", "web/preview", Context);
Command.Print (Module.all, "wiki_preview_template", "", Context);
Command.Print (Module.all, "wiki_preview_html", "", Context);
Command.Print (Module.all, "wiki_preview_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("counters");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Counter Module");
Context.Console.Notice (N_INFO, "--------------");
Command.Print (Module.all, "counter_age_limit", "300", Context);
Command.Print (Module.all, "counter_limit", "1000", Context);
end if;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
Command_Drivers.Application_Command_Type (Command).Setup (Config, Context);
GC.Define_Switch (Config => Config,
Output => Command.Long_List'Access,
Switch => "-l",
Long_Switch => "--long-lines",
Help => -("Use long lines to print configuration values"));
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
begin
Command_Drivers.Driver.Add_Command ("info",
-("report configuration information"),
Command'Access);
end AWA.Commands.Info;
|
-----------------------------------------------------------------------
-- akt-commands-info -- Info command to describe the current configuration
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Commands.Info is
use type AWA.Modules.Module_Access;
-- ------------------------------
-- Print the configuration identified by the given name.
-- ------------------------------
procedure Print (Command : in out Command_Type;
Name : in String;
Value : in String;
Default : in String;
Context : in out Context_Type) is
pragma Unreferenced (Default);
Pos : Natural;
begin
Context.Console.Start_Row;
Context.Console.Print_Field (1, Name);
Pos := Value'First;
while Pos <= Value'Last loop
if Value'Last - Pos > Command.Value_Length then
Context.Console.Print_Field (2, Value (Pos .. Pos + Command.Value_Length - 1));
Pos := Pos + Command.Value_Length;
Context.Console.End_Row;
Context.Console.Start_Row;
Context.Console.Print_Field (1, "");
else
Context.Console.Print_Field (2, Value (Pos .. Value'Last));
Pos := Pos + Value'Length;
end if;
end loop;
Context.Console.End_Row;
end Print;
procedure Print (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Application.Get_Init_Parameter (Name, Default);
begin
Command.Print (Name, Value, Default, Context);
end Print;
procedure Print (Command : in out Command_Type;
Module : in AWA.Modules.Module'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Module.Get_Config (Name, Default);
begin
Command.Print (Module.Get_Name & "." & Name, Value, Default, Context);
end Print;
-- ------------------------------
-- Print the configuration about the application.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Args);
Module : AWA.Modules.Module_Access;
begin
if Command.Long_List then
Command.Value_Length := Natural'Last;
end if;
Application.Load_Bundle (Name => "commands",
Locale => "en",
Bundle => Command.Bundle);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Database configuration");
Context.Console.Notice (N_INFO, "----------------------");
Command.Print (Application, "database", "", Context);
Command.Print (Application, "ado.queries.paths", "", Context);
Command.Print (Application, "ado.queries.load", "", Context);
Command.Print (Application, "ado.drivers.load", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Server faces configuration");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "view.dir",
ASF.Applications.DEF_VIEW_DIR, Context);
Command.Print (Application, "view.escape_unknown_tags",
ASF.Applications.DEF_ESCAPE_UNKNOWN_TAGS, Context);
Command.Print (Application, "view.ext",
ASF.Applications.DEF_VIEW_EXT, Context);
Command.Print (Application, "view.file_ext",
ASF.Applications.DEF_VIEW_FILE_EXT, Context);
Command.Print (Application, "view.ignore_spaces",
ASF.Applications.DEF_IGNORE_WHITE_SPACES, Context);
Command.Print (Application, "view.ignore_empty_lines",
ASF.Applications.DEF_IGNORE_EMPTY_LINES, Context);
Command.Print (Application, "view.static.dir",
ASF.Applications.DEF_STATIC_DIR, Context);
Command.Print (Application, "bundle.dir", "bundles", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "AWA Application");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "app_name", "", Context);
Command.Print (Application, "app_search_dirs", ".", Context);
Command.Print (Application, "app.modules.dir", "", Context);
Command.Print (Application, "app_url_base", "", Context);
Command.Print (Application, "awa_url_host", "", Context);
Command.Print (Application, "awa_url_port", "", Context);
Command.Print (Application, "awa_url_scheme", "", Context);
Command.Print (Application, "app.config", "awa.xml", Context);
Command.Print (Application, "app.config.plugins", "", Context);
Command.Print (Application, "contextPath", "", Context);
Command.Print (Application, "awa_dispatcher_count", "", Context);
Command.Print (Application, "awa_dispatcher_priority", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Users Module");
Context.Console.Notice (N_INFO, "------------");
Command.Print (Application, "openid.realm", "", Context);
Command.Print (Application, "openid.callback_url", "", Context);
Command.Print (Application, "openid.success_url", "", Context);
Command.Print (Application, "auth.url.orange", "", Context);
Command.Print (Application, "auth.provider.orange", "", Context);
Command.Print (Application, "auth.url.yahoo", "", Context);
Command.Print (Application, "auth.provider.yahoo", "", Context);
Command.Print (Application, "auth.url.google", "", Context);
Command.Print (Application, "auth.provider.google", "", Context);
Command.Print (Application, "auth.url.facebook", "", Context);
Command.Print (Application, "auth.provider.facebook", "", Context);
Command.Print (Application, "auth.url.google-plus", "", Context);
Command.Print (Application, "auth.provider.google-plus", "", Context);
Command.Print (Application, "facebook.callback_url", "", Context);
Command.Print (Application, "facebook.request_url", "", Context);
Command.Print (Application, "facebook.scope", "", Context);
Command.Print (Application, "facebook.client_id", "", Context);
Command.Print (Application, "facebook.secret", "", Context);
Command.Print (Application, "google-plus.issuer", "", Context);
Command.Print (Application, "google-plus.callback_url", "", Context);
Command.Print (Application, "google-plus.request_url", "", Context);
Command.Print (Application, "google-plus.scope", "", Context);
Command.Print (Application, "google-plus.client_id", "", Context);
Command.Print (Application, "google-plus.secret", "", Context);
Command.Print (Application, "auth-filter.redirect", "", Context);
Command.Print (Application, "verify-filter.redirect", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Mail Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Application, "mail.smtp.host", "", Context);
Command.Print (Application, "mail.smtp.port", "", Context);
Command.Print (Application, "mail.smtp.enable", "true", Context);
Command.Print (Application, "mail.mailer", "smtp", Context);
Command.Print (Application, "mail.file.maildir", "mail", Context);
Command.Print (Application, "app_mail_name", "", Context);
Command.Print (Application, "app_mail_from", "", Context);
Module := Application.Find_Module ("workspaces");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Workspace Module");
Context.Console.Notice (N_INFO, "----------------");
Command.Print (Module.all, "permissions_list", "", Context);
Command.Print (Module.all, "allow_workspace_create", "", Context);
end if;
Module := Application.Find_Module ("storages");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Storage Module");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Module.all, "database_max_size", "100000", Context);
Command.Print (Module.all, "storage_root", "storage", Context);
Command.Print (Module.all, "tmp_storage_root", "tmp", Context);
Module := Application.Find_Module ("images");
if Module /= null then
Command.Print (Module.all, "thumbnail_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("wikis");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Wiki Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Module.all, "image_prefix", "", Context);
Command.Print (Module.all, "page_prefix", "", Context);
Command.Print (Module.all, "wiki_copy_list", "", Context);
Module := Application.Find_Module ("wiki_previews");
if Module /= null then
Command.Print (Module.all, "wiki_preview_tmp", "tmp", Context);
Command.Print (Module.all, "wiki_preview_dir", "web/preview", Context);
Command.Print (Module.all, "wiki_preview_template", "", Context);
Command.Print (Module.all, "wiki_preview_html", "", Context);
Command.Print (Module.all, "wiki_preview_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("counters");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Counter Module");
Context.Console.Notice (N_INFO, "--------------");
Command.Print (Module.all, "counter_age_limit", "300", Context);
Command.Print (Module.all, "counter_limit", "1000", Context);
end if;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
Command_Drivers.Application_Command_Type (Command).Setup (Config, Context);
GC.Define_Switch (Config => Config,
Output => Command.Long_List'Access,
Switch => "-l",
Long_Switch => "--long-lines",
Help => -("Use long lines to print configuration values"));
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
begin
Command_Drivers.Driver.Add_Command ("info",
-("report configuration information"),
Command'Access);
end AWA.Commands.Info;
|
Fix list of configuration parameters
|
Fix list of configuration parameters
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f723c8922f242892e6feea760dcd994d7252435f
|
src/asf-components-html-text.adb
|
src/asf-components-html-text.adb
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with EL.Objects;
with ASF.Components.Core;
with ASF.Utils;
package body ASF.Components.Html.Text is
use EL.Objects;
TEXT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
LABEL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
-- ------------------------------
overriding
function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object is
begin
return UI.Value;
end Get_Local_Value;
-- ------------------------------
-- Get the value to write on the output.
-- ------------------------------
overriding
function Get_Value (UI : in UIOutput) return EL.Objects.Object is
begin
if not EL.Objects.Is_Null (UI.Value) then
return UI.Value;
else
return UI.Get_Attribute (UI.Get_Context.all, "value");
end if;
end Get_Value;
-- ------------------------------
-- Set the value to write on the output.
-- ------------------------------
overriding
procedure Set_Value (UI : in out UIOutput;
Value : in EL.Objects.Object) is
begin
UI.Value := Value;
end Set_Value;
-- ------------------------------
-- Get the converter that is registered on the component.
-- ------------------------------
overriding
function Get_Converter (UI : in UIOutput)
return ASF.Converters.Converter_Access is
begin
return UI.Converter;
end Get_Converter;
-- ------------------------------
-- Set the converter to be used on the component.
-- ------------------------------
overriding
procedure Set_Converter (UI : in out UIOutput;
Converter : in ASF.Converters.Converter_Access) is
use type ASF.Converters.Converter_Access;
begin
if Converter = null then
UI.Converter := null;
else
UI.Converter := Converter.all'Unchecked_Access;
end if;
end Set_Converter;
-- ------------------------------
-- Get the value of the component and apply the converter on it if there is one.
-- ------------------------------
function Get_Formatted_Value (UI : in UIOutput;
Context : in Faces_Context'Class) return String is
Value : constant EL.Objects.Object := UIOutput'Class (UI).Get_Value;
begin
return UIOutput'Class (UI).Get_Formatted_Value (Value, Context);
end Get_Formatted_Value;
-- ------------------------------
-- Format the value by appling the To_String converter on it if there is one.
-- ------------------------------
function Get_Formatted_Value (UI : in UIOutput;
Value : in Util.Beans.Objects.Object;
Context : in Contexts.Faces.Faces_Context'Class) return String is
use type ASF.Converters.Converter_Access;
begin
if UI.Converter /= null then
return UI.Converter.To_String (Context => Context,
Component => UI,
Value => Value);
else
declare
Converter : constant access ASF.Converters.Converter'Class
:= UI.Get_Converter (Context);
begin
if Converter /= null then
return Converter.To_String (Context => Context,
Component => UI,
Value => Value);
elsif not Is_Null (Value) then
return EL.Objects.To_String (Value);
else
return "";
end if;
end;
end if;
-- If the converter raises an exception, report an error in the logs.
-- At this stage, we know the value and we can report it in this log message.
-- We must queue the exception in the context, so this is done later.
exception
when E : others =>
UI.Log_Error ("Error when converting value '{0}': {1}: {2}",
Util.Beans.Objects.To_String (Value),
Ada.Exceptions.Exception_Name (E),
Ada.Exceptions.Exception_Message (E));
raise;
end Get_Formatted_Value;
procedure Write_Output (UI : in UIOutput;
Context : in out Faces_Context'Class;
Value : in String) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Escape : constant Object := UI.Get_Attribute (Context, "escape");
begin
Writer.Start_Optional_Element ("span");
UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer);
if Is_Null (Escape) or To_Boolean (Escape) then
Writer.Write_Text (Value);
else
Writer.Write_Raw (Value);
end if;
Writer.End_Optional_Element ("span");
end Write_Output;
procedure Encode_Begin (UI : in UIOutput;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
UI.Write_Output (Context => Context,
Value => UIOutput'Class (UI).Get_Formatted_Value (Context));
end if;
-- Queue any block converter exception that could be raised.
exception
when E : others =>
Context.Queue_Exception (E);
end Encode_Begin;
-- ------------------------------
-- Label Component
-- ------------------------------
procedure Encode_Begin (UI : in UIOutputLabel;
Context : in out Faces_Context'Class) is
Writer : Response_Writer_Access;
begin
if UI.Is_Rendered (Context) then
Writer := Context.Get_Response_Writer;
Writer.Start_Element ("label");
UI.Render_Attributes (Context, LABEL_ATTRIBUTE_NAMES, Writer);
declare
Value : Util.Beans.Objects.Object := UI.Get_Attribute (Name => "for",
Context => Context);
begin
if not Util.Beans.Objects.Is_Null (Value) then
Writer.Write_Attribute ("for", Value);
end if;
Value := UIOutputLabel'Class (UI).Get_Value;
if not Util.Beans.Objects.Is_Null (Value) then
declare
S : constant String
:= UIOutputLabel'Class (UI).Get_Formatted_Value (Value, Context);
begin
if UI.Get_Attribute (Name => "escape", Context => Context, Default => True) then
Writer.Write_Text (S);
else
Writer.Write_Raw (S);
end if;
end;
end if;
-- Queue and block any converter exception that could be raised.
exception
when E : others =>
Context.Queue_Exception (E);
end;
end if;
end Encode_Begin;
procedure Encode_End (UI : in UIOutputLabel;
Context : in out Faces_Context'Class) is
Writer : Response_Writer_Access;
begin
if UI.Is_Rendered (Context) then
Writer := Context.Get_Response_Writer;
Writer.End_Element ("label");
end if;
end Encode_End;
-- ------------------------------
-- OutputFormat Component
-- ------------------------------
procedure Encode_Begin (UI : in UIOutputFormat;
Context : in out Faces_Context'Class) is
use ASF.Components.Core;
use ASF.Utils;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Params : constant UIParameter_Access_Array := Get_Parameters (UI);
Values : ASF.Utils.Object_Array (Params'Range);
Result : Ada.Strings.Unbounded.Unbounded_String;
Fmt : constant String := EL.Objects.To_String (UI.Get_Value);
begin
-- Get the values associated with the parameters.
for I in Params'Range loop
Values (I) := Params (I).Get_Value (Context);
end loop;
Formats.Format (Fmt, Values, Result);
UI.Write_Output (Context => Context,
Value => To_String (Result));
end;
end Encode_Begin;
begin
Utils.Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES);
Utils.Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES);
Utils.Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES);
end ASF.Components.Html.Text;
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with EL.Objects;
with ASF.Components.Core;
with ASF.Utils;
package body ASF.Components.Html.Text is
use EL.Objects;
TEXT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
LABEL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
-- ------------------------------
overriding
function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object is
begin
return UI.Value;
end Get_Local_Value;
-- ------------------------------
-- Get the value to write on the output.
-- ------------------------------
overriding
function Get_Value (UI : in UIOutput) return EL.Objects.Object is
begin
if not EL.Objects.Is_Null (UI.Value) then
return UI.Value;
else
return UI.Get_Attribute (UI.Get_Context.all, "value");
end if;
end Get_Value;
-- ------------------------------
-- Set the value to write on the output.
-- ------------------------------
overriding
procedure Set_Value (UI : in out UIOutput;
Value : in EL.Objects.Object) is
begin
UI.Value := Value;
end Set_Value;
-- ------------------------------
-- Get the converter that is registered on the component.
-- ------------------------------
overriding
function Get_Converter (UI : in UIOutput)
return ASF.Converters.Converter_Access is
begin
return UI.Converter;
end Get_Converter;
-- ------------------------------
-- Set the converter to be used on the component.
-- ------------------------------
overriding
procedure Set_Converter (UI : in out UIOutput;
Converter : in ASF.Converters.Converter_Access;
Release : in Boolean := False) is
use type ASF.Converters.Converter_Access;
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Converters.Converter'Class,
Name => ASF.Converters.Converter_Access);
begin
if UI.Release_Converter then
Free (UI.Converter);
end if;
if Converter = null then
UI.Converter := null;
UI.Release_Converter := False;
else
UI.Converter := Converter.all'Unchecked_Access;
UI.Release_Converter := Release;
end if;
end Set_Converter;
-- ------------------------------
-- Get the value of the component and apply the converter on it if there is one.
-- ------------------------------
function Get_Formatted_Value (UI : in UIOutput;
Context : in Faces_Context'Class) return String is
Value : constant EL.Objects.Object := UIOutput'Class (UI).Get_Value;
begin
return UIOutput'Class (UI).Get_Formatted_Value (Value, Context);
end Get_Formatted_Value;
-- ------------------------------
-- Format the value by appling the To_String converter on it if there is one.
-- ------------------------------
function Get_Formatted_Value (UI : in UIOutput;
Value : in Util.Beans.Objects.Object;
Context : in Contexts.Faces.Faces_Context'Class) return String is
use type ASF.Converters.Converter_Access;
begin
if UI.Converter /= null then
return UI.Converter.To_String (Context => Context,
Component => UI,
Value => Value);
else
declare
Converter : constant access ASF.Converters.Converter'Class
:= UI.Get_Converter (Context);
begin
if Converter /= null then
return Converter.To_String (Context => Context,
Component => UI,
Value => Value);
elsif not Is_Null (Value) then
return EL.Objects.To_String (Value);
else
return "";
end if;
end;
end if;
-- If the converter raises an exception, report an error in the logs.
-- At this stage, we know the value and we can report it in this log message.
-- We must queue the exception in the context, so this is done later.
exception
when E : others =>
UI.Log_Error ("Error when converting value '{0}': {1}: {2}",
Util.Beans.Objects.To_String (Value),
Ada.Exceptions.Exception_Name (E),
Ada.Exceptions.Exception_Message (E));
raise;
end Get_Formatted_Value;
procedure Write_Output (UI : in UIOutput;
Context : in out Faces_Context'Class;
Value : in String) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Escape : constant Object := UI.Get_Attribute (Context, "escape");
begin
Writer.Start_Optional_Element ("span");
UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer);
if Is_Null (Escape) or To_Boolean (Escape) then
Writer.Write_Text (Value);
else
Writer.Write_Raw (Value);
end if;
Writer.End_Optional_Element ("span");
end Write_Output;
procedure Encode_Begin (UI : in UIOutput;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
UI.Write_Output (Context => Context,
Value => UIOutput'Class (UI).Get_Formatted_Value (Context));
end if;
-- Queue any block converter exception that could be raised.
exception
when E : others =>
Context.Queue_Exception (E);
end Encode_Begin;
overriding
procedure Finalize (UI : in out UIOutput) is
begin
UI.Set_Converter (null);
end Finalize;
-- ------------------------------
-- Label Component
-- ------------------------------
procedure Encode_Begin (UI : in UIOutputLabel;
Context : in out Faces_Context'Class) is
Writer : Response_Writer_Access;
begin
if UI.Is_Rendered (Context) then
Writer := Context.Get_Response_Writer;
Writer.Start_Element ("label");
UI.Render_Attributes (Context, LABEL_ATTRIBUTE_NAMES, Writer);
declare
Value : Util.Beans.Objects.Object := UI.Get_Attribute (Name => "for",
Context => Context);
begin
if not Util.Beans.Objects.Is_Null (Value) then
Writer.Write_Attribute ("for", Value);
end if;
Value := UIOutputLabel'Class (UI).Get_Value;
if not Util.Beans.Objects.Is_Null (Value) then
declare
S : constant String
:= UIOutputLabel'Class (UI).Get_Formatted_Value (Value, Context);
begin
if UI.Get_Attribute (Name => "escape", Context => Context, Default => True) then
Writer.Write_Text (S);
else
Writer.Write_Raw (S);
end if;
end;
end if;
-- Queue and block any converter exception that could be raised.
exception
when E : others =>
Context.Queue_Exception (E);
end;
end if;
end Encode_Begin;
procedure Encode_End (UI : in UIOutputLabel;
Context : in out Faces_Context'Class) is
Writer : Response_Writer_Access;
begin
if UI.Is_Rendered (Context) then
Writer := Context.Get_Response_Writer;
Writer.End_Element ("label");
end if;
end Encode_End;
-- ------------------------------
-- OutputFormat Component
-- ------------------------------
procedure Encode_Begin (UI : in UIOutputFormat;
Context : in out Faces_Context'Class) is
use ASF.Components.Core;
use ASF.Utils;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Params : constant UIParameter_Access_Array := Get_Parameters (UI);
Values : ASF.Utils.Object_Array (Params'Range);
Result : Ada.Strings.Unbounded.Unbounded_String;
Fmt : constant String := EL.Objects.To_String (UI.Get_Value);
begin
-- Get the values associated with the parameters.
for I in Params'Range loop
Values (I) := Params (I).Get_Value (Context);
end loop;
Formats.Format (Fmt, Values, Result);
UI.Write_Output (Context => Context,
Value => To_String (Result));
end;
end Encode_Begin;
begin
Utils.Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES);
Utils.Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES);
Utils.Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES);
end ASF.Components.Html.Text;
|
Implement the Finalize procedure to release the converter if there was one Add a Release parameter to Set_Converter and release the previous converter if it was marked with release flag
|
Implement the Finalize procedure to release the converter if there was one
Add a Release parameter to Set_Converter and release the previous converter if it was marked with release flag
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
9d652e72b77fcb3144cfe8261af202bb44f4e32e
|
src/gen-commands-templates.ads
|
src/gen-commands-templates.ads
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- 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.Containers.Vectors;
with Util.Strings.Sets;
package Gen.Commands.Templates is
-- ------------------------------
-- Template Generic Command
-- ------------------------------
-- This command adds a XHTML page to the web application.
type Command is new Gen.Commands.Command with private;
type Command_Access is access all Command'Class;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Read the template commands defined in dynamo configuration directory.
procedure Read_Commands (Generator : in out Gen.Generator.Handler);
private
type Param is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Argument : Ada.Strings.Unbounded.Unbounded_String;
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Optional : Boolean := False;
end record;
package Param_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Param);
type Command is new Gen.Commands.Command with record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
Help_Msg : Ada.Strings.Unbounded.Unbounded_String;
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Templates : Util.Strings.Sets.Set;
Params : Param_Vectors.Vector;
end record;
end Gen.Commands.Templates;
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- Copyright (C) 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with Util.Strings.Sets;
with Util.Strings.Vectors;
package Gen.Commands.Templates is
-- ------------------------------
-- Template Generic Command
-- ------------------------------
-- This command adds a XHTML page to the web application.
type Command is new Gen.Commands.Command with private;
type Command_Access is access all Command'Class;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Read the template commands defined in dynamo configuration directory.
procedure Read_Commands (Generator : in out Gen.Generator.Handler);
private
type Param is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Argument : Ada.Strings.Unbounded.Unbounded_String;
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Optional : Boolean := False;
end record;
package Param_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Param);
type Patch is record
Template : Ada.Strings.Unbounded.Unbounded_String;
After : Util.Strings.Vectors.Vector;
Before : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Patch_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Patch);
type Command is new Gen.Commands.Command with record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
Help_Msg : Ada.Strings.Unbounded.Unbounded_String;
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Templates : Util.Strings.Sets.Set;
Patches : Patch_Vectors.Vector;
Params : Param_Vectors.Vector;
end record;
end Gen.Commands.Templates;
|
Add support to patch files when executing some template command
|
Add support to patch files when executing some template command
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
cabbd7e07b235f633285e2900db96fe612d7ff02
|
matp/regtests/mat-memory-tests.adb
|
matp/regtests/mat-memory-tests.adb
|
-----------------------------------------------------------------------
-- mat-memory-tests -- Unit tests for MAT memory
-- 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.Test_Caller;
with MAT.Expressions;
with MAT.Memory.Targets;
package body MAT.Memory.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Memory");
-- Builtin and well known definition of test frames.
Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) :=
(1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc",
Test_Probe_Malloc'Access);
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free",
Test_Probe_Free'Access);
end Add_Tests;
-- ------------------------------
-- Basic consistency checks when creating the test tree
-- ------------------------------
procedure Test_Probe_Malloc (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
begin
S.Size := 4;
M.Create_Frame (Frame_1_0, S.Frame);
-- Create memory slots:
-- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104]
for I in 1 .. 10 loop
M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S);
end loop;
-- Search for a memory region that does not overlap a memory slot.
M.Find (15, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [15 .. 19]");
M.Find (1, 9, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [1 .. 9]");
M.Find (105, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [105 .. 1000]");
-- Search with an overlap.
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 10, Integer (R.Length),
"Find must return 10 slots in range [1 .. 1000]");
R.Clear;
M.Find (1, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [1 .. 19]");
R.Clear;
M.Find (13, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [13 .. 19]");
R.Clear;
M.Find (100, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [100 .. 1000]");
R.Clear;
M.Find (101, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [101 .. 1000]");
end Test_Probe_Malloc;
-- ------------------------------
-- Test Probe_Free with update of memory slots.
-- ------------------------------
procedure Test_Probe_Free (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
begin
S.Size := 4;
M.Create_Frame (Frame_1_0, S.Frame);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
M.Probe_Free (10, S);
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slot after a free");
-- Free the same slot a second time (free error).
M.Probe_Free (10, S);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
M.Probe_Malloc (20, S);
M.Probe_Malloc (30, S);
M.Probe_Free (20, S);
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 2, Integer (R.Length),
"Find must return 2 slots after a malloc/free sequence");
end Test_Probe_Free;
end MAT.Memory.Tests;
|
-----------------------------------------------------------------------
-- mat-memory-tests -- Unit tests for MAT memory
-- 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.Test_Caller;
with MAT.Expressions;
with MAT.Memory.Targets;
package body MAT.Memory.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Memory");
-- Builtin and well known definition of test frames.
Frame_1_0 : constant MAT.Frames.Frame_Table (1 .. 10) :=
(1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Malloc",
Test_Probe_Malloc'Access);
Caller.Add_Test (Suite, "Test MAT.Memory.Probe_Free",
Test_Probe_Free'Access);
end Add_Tests;
-- ------------------------------
-- Basic consistency checks when creating the test tree
-- ------------------------------
procedure Test_Probe_Malloc (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
begin
S.Size := 4;
M.Create_Frame (Frame_1_0, S.Frame);
-- Create memory slots:
-- [10 .. 14] [20 .. 24] [30 ..34] .. [100 .. 104]
for I in 1 .. 10 loop
M.Probe_Malloc (MAT.Types.Target_Addr (10 * I), S);
end loop;
-- Search for a memory region that does not overlap a memory slot.
M.Find (15, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [15 .. 19]");
M.Find (1, 9, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [1 .. 9]");
M.Find (105, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slots in range [105 .. 1000]");
-- Search with an overlap.
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 10, Integer (R.Length),
"Find must return 10 slots in range [1 .. 1000]");
R.Clear;
M.Find (1, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [1 .. 19]");
R.Clear;
M.Find (13, 19, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [13 .. 19]");
R.Clear;
M.Find (100, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [100 .. 1000]");
R.Clear;
M.Find (101, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 1, Integer (R.Length),
"Find must return 1 slot in range [101 .. 1000]");
end Test_Probe_Malloc;
-- ------------------------------
-- Test Probe_Free with update of memory slots.
-- ------------------------------
procedure Test_Probe_Free (T : in out Test) is
M : MAT.Memory.Targets.Target_Memory;
S : Allocation;
R : Allocation_Map;
Size : MAT.Types.Target_Size;
Id : MAT.Events.Targets.Event_Id_Type;
begin
S.Size := 4;
M.Create_Frame (Frame_1_0, S.Frame);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
M.Probe_Free (10, S, Size, Id);
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 0, Integer (R.Length),
"Find must return 0 slot after a free");
-- Free the same slot a second time (free error).
M.Probe_Free (10, S, Size, Id);
-- Malloc followed by a free.
M.Probe_Malloc (10, S);
M.Probe_Malloc (20, S);
M.Probe_Malloc (30, S);
M.Probe_Free (20, S, Size, Id);
M.Find (1, 1000, MAT.Expressions.EMPTY, R);
Util.Tests.Assert_Equals (T, 2, Integer (R.Length),
"Find must return 2 slots after a malloc/free sequence");
end Test_Probe_Free;
end MAT.Memory.Tests;
|
Update the unit tests
|
Update the unit tests
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
04690658ddc2232b4b7427b0213facc7034c9a57
|
src/asf-components-html-lists.adb
|
src/asf-components-html-lists.adb
|
-----------------------------------------------------------------------
-- html.lists -- List of items
-- Copyright (C) 2009, 2010, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Basic;
with ASF.Components.Base;
package body ASF.Components.Html.Lists is
use Util.Log;
use type EL.Objects.Data_Type;
Log : constant Loggers.Logger := Loggers.Create ("ASF.Components.Html.Lists");
-- ------------------------------
-- Get the value to write on the output.
-- ------------------------------
function Get_Value (UI : in UIList) return EL.Objects.Object is
begin
return UI.Get_Attribute (UI.Get_Context.all, "value");
end Get_Value;
-- ------------------------------
-- Set the value to write on the output.
-- ------------------------------
procedure Set_Value (UI : in out UIList;
Value : in EL.Objects.Object) is
begin
null;
end Set_Value;
-- ------------------------------
-- Get the variable name
-- ------------------------------
function Get_Var (UI : in UIList) return String is
Var : constant EL.Objects.Object := UI.Get_Attribute (UI.Get_Context.all, "var");
begin
return EL.Objects.To_String (Var);
end Get_Var;
procedure Encode_Children (UI : in UIList;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Value : EL.Objects.Object := Get_Value (UI);
Kind : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value);
Name : constant String := UI.Get_Var;
Bean : access Util.Beans.Basic.Readonly_Bean'Class;
Is_Reverse : constant Boolean := UI.Get_Attribute ("reverse", Context, False);
List : Util.Beans.Basic.List_Bean_Access;
Count : Natural;
begin
-- Check that we have a List_Bean but do not complain if we have a null value.
if Kind /= EL.Objects.TYPE_BEAN then
if Kind /= EL.Objects.TYPE_NULL then
ASF.Components.Base.Log_Error (UI, "Invalid list bean (found a {0})",
EL.Objects.Get_Type_Name (Value));
end if;
return;
end if;
Bean := EL.Objects.To_Bean (Value);
if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then
ASF.Components.Base.Log_Error (UI, "Invalid list bean: "
& "it does not implement 'List_Bean' interface");
return;
end if;
List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access;
Count := List.Get_Count;
if Is_Reverse then
for I in reverse 1 .. Count loop
List.Set_Row_Index (I);
Value := List.Get_Row;
Context.Set_Attribute (Name, Value);
Log.Debug ("Set variable {0}", Name);
Base.UIComponent (UI).Encode_Children (Context);
end loop;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
Value := List.Get_Row;
Context.Set_Attribute (Name, Value);
Log.Debug ("Set variable {0}", Name);
Base.UIComponent (UI).Encode_Children (Context);
end loop;
end if;
end;
end Encode_Children;
end ASF.Components.Html.Lists;
|
-----------------------------------------------------------------------
-- html.lists -- List of items
-- Copyright (C) 2009, 2010, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Basic;
with ASF.Components.Base;
package body ASF.Components.Html.Lists is
use type EL.Objects.Data_Type;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Components.Html.Lists");
function Get_Item_Layout (List_Layout : in String;
Item_Class : in String) return String;
-- ------------------------------
-- Get the list layout to use. The default is to use no layout or a div if some CSS style
-- is applied on the list or some specific list ID must be generated. Possible layout values
-- include:
-- "simple" : the list is rendered as is or as a div with each children as is,
-- "unorderedList" : the list is rendered as an HTML ul/li list,
-- "orderedList" : the list is rendered as an HTML ol/li list.
-- ------------------------------
function Get_Layout (UI : in UIList;
Class : in String;
Context : in Faces_Context'Class) return String is
Value : constant EL.Objects.Object := UI.Get_Attribute (Context, "layout");
Layout : constant String := EL.Objects.To_String (Value);
begin
if Layout = "orderedList" or Layout = "ordered" then
return "ol";
elsif Layout = "unorderedList" or Layout = "unordered" then
return "ul";
elsif Class'Length > 0 or else not UI.Is_Generated_Id then
return "div";
else
return "";
end if;
end Get_Layout;
-- ------------------------------
-- Get the item layout according to the list layout and the item class (if any).
-- ------------------------------
function Get_Item_Layout (List_Layout : in String;
Item_Class : in String) return String is
begin
if List_Layout'Length = 2 then
return "li";
elsif Item_Class'Length > 0 then
return "div";
else
return "";
end if;
end Get_Item_Layout;
-- ------------------------------
-- Get the value to write on the output.
-- ------------------------------
function Get_Value (UI : in UIList) return EL.Objects.Object is
begin
return UI.Get_Attribute (UI.Get_Context.all, "value");
end Get_Value;
-- ------------------------------
-- Set the value to write on the output.
-- ------------------------------
procedure Set_Value (UI : in out UIList;
Value : in EL.Objects.Object) is
begin
null;
end Set_Value;
-- ------------------------------
-- Get the variable name
-- ------------------------------
function Get_Var (UI : in UIList) return String is
Var : constant EL.Objects.Object := UI.Get_Attribute (UI.Get_Context.all, "var");
begin
return EL.Objects.To_String (Var);
end Get_Var;
-- ------------------------------
-- Encode an item of the list with the given item layout and item class.
-- ------------------------------
procedure Encode_Item (UI : in UIList;
Item_Layout : in String;
Item_Class : in String;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
if Item_Layout'Length > 0 then
Writer.Start_Element (Item_Layout);
end if;
if Item_Class'Length > 0 then
Writer.Write_Attribute ("class", Item_Class);
end if;
Base.UIComponent (UI).Encode_Children (Context);
if Item_Layout'Length > 0 then
Writer.End_Element (Item_Layout);
end if;
end Encode_Item;
procedure Encode_Children (UI : in UIList;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Value : EL.Objects.Object := Get_Value (UI);
Kind : constant EL.Objects.Data_Type := EL.Objects.Get_Type (Value);
Name : constant String := UI.Get_Var;
Bean : access Util.Beans.Basic.Readonly_Bean'Class;
Is_Reverse : constant Boolean := UI.Get_Attribute ("reverse", Context, False);
List : Util.Beans.Basic.List_Bean_Access;
Count : Natural;
begin
-- Check that we have a List_Bean but do not complain if we have a null value.
if Kind /= EL.Objects.TYPE_BEAN then
if Kind /= EL.Objects.TYPE_NULL then
ASF.Components.Base.Log_Error (UI, "Invalid list bean (found a {0})",
EL.Objects.Get_Type_Name (Value));
end if;
return;
end if;
Bean := EL.Objects.To_Bean (Value);
if Bean = null or else not (Bean.all in Util.Beans.Basic.List_Bean'Class) then
ASF.Components.Base.Log_Error (UI, "Invalid list bean: "
& "it does not implement 'List_Bean' interface");
return;
end if;
List := Util.Beans.Basic.List_Bean'Class (Bean.all)'Unchecked_Access;
Count := List.Get_Count;
if Count /= 0 then
declare
Class : constant String := UI.Get_Attribute (STYLE_CLASS_ATTR_NAME,
Context, "");
Item_Class : constant String := UI.Get_Attribute (ITEM_STYLE_CLASS_ATTR_NAME,
Context, "");
Layout : constant String := UI.Get_Layout (Class, Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Item_Layout : constant String := Get_Item_Layout (Layout, Item_Class);
begin
if Layout'Length > 0 then
Writer.Start_Element (Layout);
end if;
if not UI.Is_Generated_Id then
Writer.Write_Attribute ("id", UI.Get_Client_Id);
end if;
if Class'Length > 0 then
Writer.Write_Attribute ("class", Class);
end if;
if Is_Reverse then
for I in reverse 1 .. Count loop
List.Set_Row_Index (I);
Value := List.Get_Row;
Context.Set_Attribute (Name, Value);
Log.Debug ("Set variable {0}", Name);
UI.Encode_Item (Item_Layout, Item_Class, Context);
end loop;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
Value := List.Get_Row;
Context.Set_Attribute (Name, Value);
Log.Debug ("Set variable {0}", Name);
UI.Encode_Item (Item_Layout, Item_Class, Context);
end loop;
end if;
if Layout'Length > 0 then
Writer.End_Element (Layout);
end if;
end;
end if;
end;
end Encode_Children;
end ASF.Components.Html.Lists;
|
Add support to render ordered and unordered lists - Implement Get_Layout and Encode_Item - Allow to render a CSS class on the list as well as on each list item
|
Add support to render ordered and unordered lists
- Implement Get_Layout and Encode_Item
- Allow to render a CSS class on the list as well as on each list item
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
5e5646a6805625ba3637672add310dd33eded603
|
tools/druss-commands-bboxes.ads
|
tools/druss-commands-bboxes.ads
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Util.Properties;
with Util.Commands;
with Druss.Gateways;
package Druss.Commands.Bboxes is
type Command_Type is new Druss.Commands.Drivers.Command_Type with null record;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Util.Commands.Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type);
end Druss.Commands.Bboxes;
|
-----------------------------------------------------------------------
-- druss-commands-bboxes -- Commands to manage the bboxes
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Druss.Commands.Bboxes is
type Command_Type is new Druss.Commands.Drivers.Command_Type with null record;
procedure Discover (Command : in Command_Type);
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
overriding
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Druss.Commands.Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type);
end Druss.Commands.Bboxes;
|
Declare the Discover procedure
|
Declare the Discover procedure
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
50806838d37c4b9c05f20a5ea3bc8445092e7ce1
|
regtests/ado-parameters-tests.adb
|
regtests/ado-parameters-tests.adb
|
-----------------------------------------------------------------------
-- ado-parameters-tests -- Test query parameters and SQL expansion
-- Copyright (C) 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
package body ADO.Parameters.Tests is
use Util.Tests;
type Dialect is new ADO.Drivers.Dialects.Dialect with null record;
-- Check if the string is a reserved keyword.
overriding
function Is_Reserved (D : in Dialect;
Name : in String) return Boolean;
-- Test the Add_Param operation for various types.
generic
type T (<>) is private;
with procedure Add_Param (L : in out ADO.Parameters.Abstract_List;
V : in T) is <>;
Value : T;
Name : String;
procedure Test_Add_Param_T (Tst : in out Test);
-- Test the Bind_Param operation for various types.
generic
type T (<>) is private;
with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List;
N : in String;
V : in T) is <>;
Value : T;
Name : String;
procedure Test_Bind_Param_T (Tst : in out Test);
-- Test the Add_Param operation for various types.
procedure Test_Add_Param_T (Tst : in out Test) is
Count : constant Positive := 100;
SQL : ADO.Parameters.List;
S : Util.Measures.Stamp;
begin
for I in 1 .. Count loop
Add_Param (ADO.Parameters.Abstract_List (SQL), Value);
end loop;
Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)");
Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name);
end Test_Add_Param_T;
-- Test the Bind_Param operation for various types.
procedure Test_Bind_Param_T (Tst : in out Test) is
Count : constant Positive := 100;
SQL : ADO.Parameters.List;
S : Util.Measures.Stamp;
begin
for I in 1 .. Count loop
Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value);
end loop;
Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)");
Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name);
end Test_Bind_Param_T;
procedure Test_Add_Param_Integer is
new Test_Add_Param_T (Integer, Add_Param, 10, "Integer");
procedure Test_Add_Param_Long_Long_Integer is
new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer");
procedure Test_Add_Param_Identifier is
new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier");
procedure Test_Add_Param_Boolean is
new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean");
procedure Test_Add_Param_String is
new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String");
procedure Test_Add_Param_Calendar is
new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time");
procedure Test_Add_Param_Unbounded_String is
new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"),
"Unbounded_String");
procedure Test_Bind_Param_Integer is
new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer");
procedure Test_Bind_Param_Long_Long_Integer is
new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000,
"Long_Long_Integer");
procedure Test_Bind_Param_Identifier is
new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier");
procedure Test_Bind_Param_Entity_Type is
new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type");
procedure Test_Bind_Param_Boolean is
new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean");
procedure Test_Bind_Param_String is
new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String");
procedure Test_Bind_Param_Calendar is
new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time");
procedure Test_Bind_Param_Unbounded_String is
new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"),
"Unbounded_String");
package Caller is new Util.Test_Caller (Test, "ADO.Parameters");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand",
Test_Expand_Sql'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)",
Test_Expand_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)",
Test_Expand_Perf'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)",
Test_Add_Param_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)",
Test_Add_Param_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)",
Test_Add_Param_Long_Long_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)",
Test_Add_Param_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)",
Test_Add_Param_Calendar'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)",
Test_Add_Param_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)",
Test_Add_Param_Unbounded_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)",
Test_Bind_Param_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)",
Test_Bind_Param_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)",
Test_Bind_Param_Long_Long_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)",
Test_Bind_Param_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)",
Test_Bind_Param_Calendar'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)",
Test_Bind_Param_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)",
Test_Bind_Param_Unbounded_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)",
Test_Bind_Param_Entity_Type'Access);
end Add_Tests;
-- ------------------------------
-- Check if the string is a reserved keyword.
-- ------------------------------
overriding
function Is_Reserved (D : in Dialect;
Name : in String) return Boolean is
pragma Unreferenced (D, Name);
begin
return False;
end Is_Reserved;
-- ------------------------------
-- Test expand SQL with parameters.
-- ------------------------------
procedure Test_Expand_Sql (T : in out Test) is
SQL : ADO.Parameters.List;
D : aliased Dialect;
procedure Check (Pattern : in String; Expect : in String);
procedure Check (Pattern : in String; Expect : in String) is
Result : constant String := SQL.Expand (Pattern);
begin
Assert_Equals (T, Expect, Result, "Invalid SQL expansion");
end Check;
begin
SQL.Set_Dialect (D'Unchecked_Access);
SQL.Bind_Param (1, "select '");
SQL.Bind_Param (2, "from");
SQL.Bind_Param ("user_id", String '("23"));
SQL.Bind_Param ("object_23_identifier", Integer (44));
SQL.Bind_Param ("bool", True);
SQL.Bind_Param (6, False);
SQL.Bind_Param ("_date", Ada.Calendar.Clock);
SQL.Bind_Null_Param ("_null");
Check ("?", "'select '''");
Check (":2", "'from'");
Check (":6", "0");
Check (":user_id", "'23'");
Check (":bool", "1");
Check (":_null", "NULL");
Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0");
Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0");
Check ("select ? :2 :user_id :object_23_identifier :bool :6",
"select 'select ''' 'from' '23' 44 1 0");
end Test_Expand_Sql;
-- ------------------------------
-- Test expand with invalid parameters.
-- ------------------------------
procedure Test_Expand_Error (T : in out Test) is
SQL : ADO.Parameters.List;
procedure Check (Pattern : in String; Expect : in String);
procedure Check (Pattern : in String; Expect : in String) is
Result : constant String := SQL.Expand (Pattern);
begin
Assert_Equals (T, Expect, Result, "Invalid SQL expansion");
end Check;
begin
Check (":<", "<");
Check (":234", "");
Check (":name", "");
Check ("select :", "select :");
end Test_Expand_Error;
-- ------------------------------
-- Test expand performance.
-- ------------------------------
procedure Test_Expand_Perf (T : in out Test) is
pragma Unreferenced (T);
SQL : ADO.Parameters.List;
D : aliased Dialect;
begin
SQL.Set_Dialect (D'Unchecked_Access);
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
SQL.Bind_Param (I, I);
end loop;
Util.Measures.Report (T, "Bind_Param (1000 calls)");
end;
declare
B : constant Unbounded_String
:= To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = 23");
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := To_String (B);
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand reference To_String");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = 23");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = :10");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)");
end;
end Test_Expand_Perf;
end ADO.Parameters.Tests;
|
-----------------------------------------------------------------------
-- ado-parameters-tests -- Test query parameters and SQL expansion
-- Copyright (C) 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
package body ADO.Parameters.Tests is
use Util.Tests;
type Dialect is new ADO.Drivers.Dialects.Dialect with null record;
-- Check if the string is a reserved keyword.
overriding
function Is_Reserved (D : in Dialect;
Name : in String) return Boolean;
-- Test the Add_Param operation for various types.
generic
type T (<>) is private;
with procedure Add_Param (L : in out ADO.Parameters.Abstract_List;
V : in T) is <>;
Value : T;
Name : String;
procedure Test_Add_Param_T (Tst : in out Test);
-- Test the Bind_Param operation for various types.
generic
type T (<>) is private;
with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List;
N : in String;
V : in T) is <>;
Value : T;
Name : String;
procedure Test_Bind_Param_T (Tst : in out Test);
-- Test the Add_Param operation for various types.
procedure Test_Add_Param_T (Tst : in out Test) is
Count : constant Positive := 100;
SQL : ADO.Parameters.List;
S : Util.Measures.Stamp;
begin
for I in 1 .. Count loop
Add_Param (ADO.Parameters.Abstract_List (SQL), Value);
end loop;
Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)");
Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name);
end Test_Add_Param_T;
-- Test the Bind_Param operation for various types.
procedure Test_Bind_Param_T (Tst : in out Test) is
Count : constant Positive := 100;
SQL : ADO.Parameters.List;
S : Util.Measures.Stamp;
begin
for I in 1 .. Count loop
Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value);
end loop;
Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)");
Util.Tests.Assert_Equals (Tst, 1, SQL.Length, "Invalid param list for " & Name);
end Test_Bind_Param_T;
procedure Test_Add_Param_Integer is
new Test_Add_Param_T (Integer, Add_Param, 10, "Integer");
procedure Test_Add_Param_Long_Long_Integer is
new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer");
procedure Test_Add_Param_Identifier is
new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier");
procedure Test_Add_Param_Boolean is
new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean");
procedure Test_Add_Param_String is
new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String");
procedure Test_Add_Param_Calendar is
new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time");
procedure Test_Add_Param_Unbounded_String is
new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"),
"Unbounded_String");
procedure Test_Bind_Param_Integer is
new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer");
procedure Test_Bind_Param_Long_Long_Integer is
new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000,
"Long_Long_Integer");
procedure Test_Bind_Param_Identifier is
new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier");
procedure Test_Bind_Param_Entity_Type is
new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type");
procedure Test_Bind_Param_Boolean is
new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean");
procedure Test_Bind_Param_String is
new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String");
procedure Test_Bind_Param_Calendar is
new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time");
procedure Test_Bind_Param_Unbounded_String is
new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"),
"Unbounded_String");
package Caller is new Util.Test_Caller (Test, "ADO.Parameters");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand",
Test_Expand_Sql'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)",
Test_Expand_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)",
Test_Expand_Perf'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)",
Test_Add_Param_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)",
Test_Add_Param_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)",
Test_Add_Param_Long_Long_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)",
Test_Add_Param_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)",
Test_Add_Param_Calendar'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)",
Test_Add_Param_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)",
Test_Add_Param_Unbounded_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)",
Test_Bind_Param_Boolean'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)",
Test_Bind_Param_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)",
Test_Bind_Param_Long_Long_Integer'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)",
Test_Bind_Param_Identifier'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)",
Test_Bind_Param_Calendar'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)",
Test_Bind_Param_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)",
Test_Bind_Param_Unbounded_String'Access);
Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)",
Test_Bind_Param_Entity_Type'Access);
end Add_Tests;
-- ------------------------------
-- Check if the string is a reserved keyword.
-- ------------------------------
overriding
function Is_Reserved (D : in Dialect;
Name : in String) return Boolean is
pragma Unreferenced (D, Name);
begin
return False;
end Is_Reserved;
-- ------------------------------
-- Test expand SQL with parameters.
-- ------------------------------
procedure Test_Expand_Sql (T : in out Test) is
SQL : ADO.Parameters.List;
D : aliased Dialect;
procedure Check (Pattern : in String; Expect : in String);
procedure Check (Pattern : in String; Expect : in String) is
Result : constant String := SQL.Expand (Pattern);
begin
Assert_Equals (T, Expect, Result, "Invalid SQL expansion");
end Check;
begin
SQL.Set_Dialect (D'Unchecked_Access);
SQL.Bind_Param (1, "select '");
SQL.Bind_Param (2, "from");
SQL.Bind_Param ("user_id", String '("23"));
SQL.Bind_Param ("object_23_identifier", Integer (44));
SQL.Bind_Param ("bool", True);
SQL.Bind_Param (6, False);
SQL.Bind_Param ("_date", Ada.Calendar.Clock);
SQL.Bind_Null_Param ("_null");
Check ("?", "'select '''");
Check (":2", "'from'");
Check (":6", "0");
Check (":user_id", "'23'");
Check (":bool", "1");
Check (":_null", "NULL");
Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0");
Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0");
Check ("select ? :2 :user_id :object_23_identifier :bool :6",
"select 'select ''' 'from' '23' 44 1 0");
end Test_Expand_Sql;
-- ------------------------------
-- Test expand with invalid parameters.
-- ------------------------------
procedure Test_Expand_Error (T : in out Test) is
SQL : ADO.Parameters.List;
procedure Check (Pattern : in String; Expect : in String);
procedure Check (Pattern : in String; Expect : in String) is
Result : constant String := SQL.Expand (Pattern);
begin
Assert_Equals (T, Expect, Result, "Invalid SQL expansion");
end Check;
begin
Check (":<", "<");
Check (":234", "");
Check (":name", "");
Check ("select :", "select :");
end Test_Expand_Error;
-- ------------------------------
-- Test expand performance.
-- ------------------------------
procedure Test_Expand_Perf (T : in out Test) is
pragma Unreferenced (T);
SQL : ADO.Parameters.List;
D : aliased Dialect;
begin
SQL.Set_Dialect (D'Unchecked_Access);
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
SQL.Bind_Param (I, I);
end loop;
Util.Measures.Report (T, "Bind_Param (1000 calls)");
end;
declare
B : constant Unbounded_String
:= To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = 23");
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := To_String (B);
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand reference To_String");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = 23");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f "
& "from T where t.b = :10");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)");
end;
declare
T : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100");
pragma Unreferenced (S);
begin
null;
end;
end loop;
Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)");
end;
end Test_Expand_Perf;
end ADO.Parameters.Tests;
|
Update the unit test
|
Update the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
31fa5d29966818dd689fabfa47270211f443cec5
|
mat/src/symbols/mat-symbols-targets.adb
|
mat/src/symbols/mat-symbols-targets.adb
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Bfd.Sections;
with ELF;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Ada.Directories;
with MAT.Formats;
package body MAT.Symbols.Targets is
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets");
procedure Find_Nearest_Line (Symbols : in Region_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Log.Info ("Loading symbols from {0}", Path);
--
-- Bfd.Files.Open (Symbols.File, Path, "");
-- if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
-- Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
-- end if;
end Open;
-- ------------------------------
-- Load the symbol table for the associated region.
-- ------------------------------
procedure Open (Symbols : in out Region_Symbols;
Path : in String;
Search_Path : in String) is
Pos : Natural;
begin
Log.Info ("Loading symbols from {0}", Path);
if Ada.Directories.Exists (Path) then
Bfd.Files.Open (Symbols.File, Path, "");
else
Pos := Util.Strings.Rindex (Path, '/');
if Pos > 0 then
Bfd.Files.Open (Symbols.File,
Util.Files.Find_File_Path (Path (Pos + 1 .. Path'Last), Search_Path));
end if;
end if;
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- 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) is
use type Bfd.File_Flags;
Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr);
Syms : Region_Symbols_Ref;
begin
if not Symbols_Maps.Has_Element (Pos) then
Syms := Region_Symbols_Refs.Create;
Syms.Value.Region := Region;
Syms.Value.Offset := Offset_Addr;
Symbols.Libraries.Insert (Region.Start_Addr, Syms);
else
Syms := Symbols_Maps.Element (Pos);
end if;
if Ada.Strings.Unbounded.Length (Region.Path) > 0 then
Open (Syms.Value, Ada.Strings.Unbounded.To_String (Region.Path),
Ada.Strings.Unbounded.To_String (Symbols.Search_Path));
if Bfd.Files.Is_Open (Syms.Value.File) and
then (Bfd.Files.Get_File_Flags (Syms.Value.File) and Bfd.Files.EXEC_P) /= 0
then
Syms.Value.Offset := 0;
end if;
end if;
end Load_Symbols;
-- ------------------------------
-- 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) is
use type ELF.Elf32_Word;
Iter : MAT.Memory.Region_Info_Cursor := Regions.First;
begin
while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop
declare
Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter);
Offset : MAT.Types.Target_Addr;
begin
if (Region.Flags and ELF.PF_X) /= 0 then
if Ada.Strings.Unbounded.Length (Region.Path) = 0 then
Region.Path := Symbols.Path;
Offset := 0;
else
Offset := Region.Start_Addr;
end if;
MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset);
end if;
exception
when Bfd.OPEN_ERROR =>
Symbols.Console.Error ("Cannot open symbol library file '"
& Ada.Strings.Unbounded.To_String (Region.Path) & "'");
end;
MAT.Memory.Region_Info_Maps.Next (Iter);
end loop;
end Load_Symbols;
-- ------------------------------
-- Demangle the symbol.
-- ------------------------------
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info) is
use type Bfd.Demangle_Flags;
Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward);
begin
if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then
return;
end if;
declare
Mode : Bfd.Demangle_Flags := Symbols.Demangle;
Len : constant Positive := Length (Symbol.File);
Ext : constant String := Slice (Symbol.File, Pos, Len);
Sym : constant String := To_String (Symbol.Name);
begin
if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then
Mode := Bfd.Constants.DMGL_GNAT;
end if;
declare
Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode);
begin
if Name'Length > 0 then
Symbol.Name := To_Unbounded_String (Name);
end if;
end;
end;
end Demangle;
procedure Find_Nearest_Line (Symbols : in Region_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info) is
Text_Section : Bfd.Sections.Section;
Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr);
begin
if not Bfd.Files.Is_Open (Symbols.File) then
Symbol.File := Symbols.Region.Path;
return;
end if;
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Pc,
Name => Symbol.File,
Func => Symbol.Name,
Line => Symbol.Line);
end Find_Nearest_Line;
-- ------------------------------
-- 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) is
Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr);
begin
Symbol.Line := 0;
if Symbols_Maps.Has_Element (Pos) then
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos);
begin
if Syms.Value.Region.End_Addr > Addr then
Symbol.Symbols := Syms;
Find_Nearest_Line (Symbols => Syms.Value,
Addr => Addr - Syms.Value.Offset,
Symbol => Symbol);
Demangle (Symbols, Symbol);
return;
end if;
exception
when Bfd.NOT_FOUND =>
Symbol.Line := 0;
Symbol.File := Syms.Value.Region.Path;
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr));
return;
end;
end if;
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr));
end Find_Nearest_Line;
-- ------------------------------
-- 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) is
use type Bfd.Symbols.Symbol;
Iter : Symbols_Cursor := Symbols.Libraries.First;
begin
while Symbols_Maps.Has_Element (Iter) loop
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter);
Sym : Bfd.Symbols.Symbol;
Sec : Bfd.Sections.Section;
begin
if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then
Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name);
if Sym /= Bfd.Symbols.Null_Symbol then
Sec := Bfd.Symbols.Get_Section (Sym);
if not Bfd.Sections.Is_Undefined_Section (Sec) then
From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym));
From := From + Syms.Value.Offset;
To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym));
return;
end if;
end if;
end if;
end;
Symbols_Maps.Next (Iter);
end loop;
end Find_Symbol_Range;
-- ------------------------------
-- 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) is
use type Bfd.Symbols.Symbol;
Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr);
begin
if Symbols_Maps.Has_Element (Pos) then
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos);
Symbol : Symbol_Info;
Sym : Bfd.Symbols.Symbol;
Sec : Bfd.Sections.Section;
begin
if Syms.Value.Region.End_Addr > Addr then
Symbol.Line := 0;
Symbol.Symbols := Syms;
Find_Nearest_Line (Symbols => Syms.Value,
Addr => Addr - Syms.Value.Offset,
Symbol => Symbol);
Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, To_String (Symbol.Name));
if Sym /= Bfd.Symbols.Null_Symbol then
Sec := Bfd.Symbols.Get_Section (Sym);
if not Bfd.Sections.Is_Undefined_Section (Sec) then
From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym));
From := From + Syms.Value.Offset;
To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym));
return;
end if;
end if;
end if;
end;
end if;
From := Addr;
To := Addr;
exception
when Bfd.NOT_FOUND =>
From := Addr;
To := Addr;
end Find_Symbol_Range;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Bfd.Sections;
with ELF;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Ada.Directories;
with MAT.Formats;
package body MAT.Symbols.Targets is
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets");
procedure Find_Nearest_Line (Symbols : in Region_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Log.Info ("Loading symbols from {0}", Path);
--
-- Bfd.Files.Open (Symbols.File, Path, "");
-- if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
-- Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
-- end if;
end Open;
-- ------------------------------
-- Load the symbol table for the associated region.
-- ------------------------------
procedure Open (Symbols : in out Region_Symbols;
Path : in String;
Search_Path : in String) is
Pos : Natural;
begin
Log.Info ("Loading symbols from {0}", Path);
if Ada.Directories.Exists (Path) then
Bfd.Files.Open (Symbols.File, Path, "");
else
Pos := Util.Strings.Rindex (Path, '/');
if Pos > 0 then
Bfd.Files.Open (Symbols.File,
Util.Files.Find_File_Path (Path (Pos + 1 .. Path'Last), Search_Path));
end if;
end if;
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- 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) is
use type Bfd.File_Flags;
Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr);
Syms : Region_Symbols_Ref;
begin
if not Symbols_Maps.Has_Element (Pos) then
Syms := Region_Symbols_Refs.Create;
Syms.Value.Region := Region;
Syms.Value.Offset := Offset_Addr;
Symbols.Libraries.Insert (Region.Start_Addr, Syms);
else
Syms := Symbols_Maps.Element (Pos);
end if;
if Ada.Strings.Unbounded.Length (Region.Path) > 0 then
Open (Syms.Value, Ada.Strings.Unbounded.To_String (Region.Path),
Ada.Strings.Unbounded.To_String (Symbols.Search_Path));
if Bfd.Files.Is_Open (Syms.Value.File) and
then (Bfd.Files.Get_File_Flags (Syms.Value.File) and Bfd.Files.EXEC_P) /= 0
then
Syms.Value.Offset := 0;
end if;
end if;
end Load_Symbols;
-- ------------------------------
-- 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) is
use type ELF.Elf32_Word;
Iter : MAT.Memory.Region_Info_Cursor := Regions.First;
begin
while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop
declare
Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter);
Offset : MAT.Types.Target_Addr;
begin
if (Region.Flags and ELF.PF_X) /= 0 then
if Ada.Strings.Unbounded.Length (Region.Path) = 0 then
Region.Path := Symbols.Path;
Offset := 0;
else
Offset := Region.Start_Addr;
end if;
MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset);
end if;
exception
when Bfd.OPEN_ERROR =>
Symbols.Console.Error ("Cannot open symbol library file '"
& Ada.Strings.Unbounded.To_String (Region.Path) & "'");
end;
MAT.Memory.Region_Info_Maps.Next (Iter);
end loop;
end Load_Symbols;
-- ------------------------------
-- Demangle the symbol.
-- ------------------------------
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info) is
use type Bfd.Demangle_Flags;
Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward);
begin
if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then
return;
end if;
declare
Mode : Bfd.Demangle_Flags := Symbols.Demangle;
Len : constant Positive := Length (Symbol.File);
Ext : constant String := Slice (Symbol.File, Pos, Len);
Sym : constant String := To_String (Symbol.Name);
begin
if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then
Mode := Bfd.Constants.DMGL_GNAT;
end if;
declare
Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode);
begin
if Name'Length > 0 then
Symbol.Name := To_Unbounded_String (Name);
end if;
end;
end;
end Demangle;
procedure Find_Nearest_Line (Symbols : in Region_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info) is
Text_Section : Bfd.Sections.Section;
Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr);
begin
if not Bfd.Files.Is_Open (Symbols.File) then
Symbol.File := Symbols.Region.Path;
return;
end if;
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Pc,
Name => Symbol.File,
Func => Symbol.Name,
Line => Symbol.Line);
end Find_Nearest_Line;
-- ------------------------------
-- 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) is
Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr);
begin
Symbol.Line := 0;
if Symbols_Maps.Has_Element (Pos) then
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos);
begin
if Syms.Value.Region.End_Addr > Addr then
Symbol.Symbols := Syms;
Find_Nearest_Line (Symbols => Syms.Value,
Addr => Addr - Syms.Value.Offset,
Symbol => Symbol);
if Symbols.Use_Demangle then
Demangle (Symbols, Symbol);
end if;
return;
end if;
exception
when Bfd.NOT_FOUND =>
Symbol.Line := 0;
Symbol.File := Syms.Value.Region.Path;
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr));
return;
end;
end if;
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr));
end Find_Nearest_Line;
-- ------------------------------
-- 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) is
use type Bfd.Symbols.Symbol;
Iter : Symbols_Cursor := Symbols.Libraries.First;
begin
while Symbols_Maps.Has_Element (Iter) loop
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter);
Sym : Bfd.Symbols.Symbol;
Sec : Bfd.Sections.Section;
begin
if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then
Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name);
if Sym /= Bfd.Symbols.Null_Symbol then
Sec := Bfd.Symbols.Get_Section (Sym);
if not Bfd.Sections.Is_Undefined_Section (Sec) then
From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym));
From := From + Syms.Value.Offset;
To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym));
return;
end if;
end if;
end if;
end;
Symbols_Maps.Next (Iter);
end loop;
end Find_Symbol_Range;
-- ------------------------------
-- 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) is
use type Bfd.Symbols.Symbol;
Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr);
begin
if Symbols_Maps.Has_Element (Pos) then
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos);
Symbol : Symbol_Info;
Sym : Bfd.Symbols.Symbol;
Sec : Bfd.Sections.Section;
begin
if Syms.Value.Region.End_Addr > Addr then
Symbol.Line := 0;
Symbol.Symbols := Syms;
Find_Nearest_Line (Symbols => Syms.Value,
Addr => Addr - Syms.Value.Offset,
Symbol => Symbol);
Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, To_String (Symbol.Name));
if Sym /= Bfd.Symbols.Null_Symbol then
Sec := Bfd.Symbols.Get_Section (Sym);
if not Bfd.Sections.Is_Undefined_Section (Sec) then
From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym));
From := From + Syms.Value.Offset;
To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym));
return;
end if;
end if;
end if;
end;
end if;
From := Addr;
To := Addr;
exception
when Bfd.NOT_FOUND =>
From := Addr;
To := Addr;
end Find_Symbol_Range;
end MAT.Symbols.Targets;
|
Use the demangler only when it is enabled
|
Use the demangler only when it is enabled
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
361e2f56c40120a19e8574be3f45f142debe239b
|
src/xml/util-serialize-io-xml.adb
|
src/xml/util-serialize-io-xml.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- 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 Unicode;
with Unicode.CES.Utf8;
with Util.Log.Loggers;
package body Util.Serialize.IO.XML is
use Util.Log;
use Sax.Readers;
use Sax.Exceptions;
use Sax.Locators;
use Sax.Attributes;
use Unicode;
use Unicode.CES;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.XML");
-- ------------------------------
-- Warning
-- ------------------------------
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Warn ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Warning;
-- ------------------------------
-- Error
-- ------------------------------
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Error;
-- ------------------------------
-- Fatal_Error
-- ------------------------------
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Unreferenced (Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Fatal_Error;
-- ------------------------------
-- Set_Document_Locator
-- ------------------------------
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator) is
begin
Handler.Locator := Loc;
end Set_Document_Locator;
-- ------------------------------
-- Start_Document
-- ------------------------------
overriding
procedure Start_Document (Handler : in out Xhtml_Reader) is
begin
null;
end Start_Document;
-- ------------------------------
-- End_Document
-- ------------------------------
overriding
procedure End_Document (Handler : in out Xhtml_Reader) is
begin
null;
end End_Document;
-- ------------------------------
-- Start_Prefix_Mapping
-- ------------------------------
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence) is
begin
null;
end Start_Prefix_Mapping;
-- ------------------------------
-- End_Prefix_Mapping
-- ------------------------------
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence) is
begin
null;
end End_Prefix_Mapping;
-- ------------------------------
-- Start_Element
-- ------------------------------
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class) is
pragma Unreferenced (Namespace_URI, Qname);
Attr_Count : Natural;
begin
-- Handler.Line.Line := Sax.Locators.Get_Line_Number (Handler.Locator);
-- Handler.Line.Column := Sax.Locators.Get_Column_Number (Handler.Locator);
Log.Debug ("Start object {0}", Local_Name);
Handler.Handler.Start_Object (Local_Name);
Attr_Count := Get_Length (Atts);
for I in 0 .. Attr_Count - 1 loop
declare
Name : constant String := Get_Qname (Atts, I);
Value : constant String := Get_Value (Atts, I);
begin
Handler.Handler.Set_Member (Name => Name,
Value => Util.Beans.Objects.To_Object (Value),
Attribute => True);
end;
end loop;
end Start_Element;
-- ------------------------------
-- End_Element
-- ------------------------------
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "") is
pragma Unreferenced (Namespace_URI, Qname);
begin
Handler.Handler.Finish_Object (Local_Name);
if Length (Handler.Text) > 0 then
Log.Debug ("Close object {0} -> {1}", Local_Name, To_String (Handler.Text));
Handler.Handler.Set_Member (Local_Name, Util.Beans.Objects.To_Object (Handler.Text));
Set_Unbounded_String (Handler.Text, "");
else
Log.Debug ("Close object {0}", Local_Name);
end if;
end End_Element;
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence) is
begin
Append (Handler.Text, Content);
end Collect_Text;
-- ------------------------------
-- Characters
-- ------------------------------
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
Collect_Text (Handler, Ch);
end Characters;
-- ------------------------------
-- Ignorable_Whitespace
-- ------------------------------
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
if not Handler.Ignore_White_Spaces then
Collect_Text (Handler, Ch);
end if;
end Ignorable_Whitespace;
-- ------------------------------
-- Processing_Instruction
-- ------------------------------
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence) is
pragma Unreferenced (Handler);
begin
Log.Error ("Processing instruction: {0}: {1}", Target, Data);
end Processing_Instruction;
-- ------------------------------
-- Skipped_Entity
-- ------------------------------
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence) is
pragma Unmodified (Handler);
begin
null;
end Skipped_Entity;
-- ------------------------------
-- Start_Cdata
-- ------------------------------
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("Start CDATA");
end Start_Cdata;
-- ------------------------------
-- End_Cdata
-- ------------------------------
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("End CDATA");
end End_Cdata;
-- ------------------------------
-- Resolve_Entity
-- ------------------------------
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access is
pragma Unreferenced (Handler);
begin
Log.Error ("Cannot resolve entity {0} - {1}", Public_Id, System_Id);
return null;
end Resolve_Entity;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "") is
begin
null;
end Start_DTD;
-- ------------------------------
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
-- ------------------------------
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_White_Spaces := Value;
end Set_Ignore_White_Spaces;
-- ------------------------------
-- Set the XHTML reader to ignore empty lines.
-- ------------------------------
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_Empty_Lines := Value;
end Set_Ignore_Empty_Lines;
-- ------------------------------
-- Parse an XML stream, and calls the appropriate SAX callbacks for each
-- event.
-- This is not re-entrant: you can not call Parse with the same Parser
-- argument in one of the SAX callbacks. This has undefined behavior.
-- ------------------------------
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
type String_Access is access all String (1 .. 32);
type Stream_Input is new Input_Sources.Input_Source with record
Index : Natural;
Last : Natural;
Encoding : Unicode.CES.Encoding_Scheme;
Buffer : String_Access;
end record;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char);
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean;
procedure Fill (From : in out Stream_Input);
procedure Fill (From : in out Stream_Input) is
begin
-- Move to the buffer start
if From.Last > From.Index and From.Index > From.Buffer'First then
From.Buffer (From.Buffer'First .. From.Last - 1 - From.Index + From.Buffer'First) :=
From.Buffer (From.Index .. From.Last - 1);
From.Last := From.Last - From.Index + From.Buffer'First;
From.Index := From.Buffer'First;
end if;
if From.Index > From.Last then
From.Index := From.Buffer'First;
end if;
begin
loop
Stream.Read (From.Buffer (From.Last));
From.Last := From.Last + 1;
exit when From.Last > From.Buffer'Last;
end loop;
exception
when others =>
null;
end;
end Fill;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char) is
begin
if From.Index + 6 >= From.Last then
Fill (From);
end if;
From.Encoding.Read (From.Buffer.all, From.Index, C);
end Next_Char;
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean is
begin
if From.Index < From.Last then
return False;
end if;
return Stream.Is_Eof;
end Eof;
Input : Stream_Input;
Xml_Parser : Xhtml_Reader;
Buf : aliased String (1 .. 32);
begin
Input.Buffer := Buf'Access;
Input.Index := 2;
Input.Last := 1;
Input.Set_Encoding (Unicode.CES.Utf8.Utf8_Encoding);
Input.Encoding := Unicode.CES.Utf8.Utf8_Encoding;
Xml_Parser.Handler := Handler'Unchecked_Access;
Xml_Parser.Ignore_White_Spaces := Handler.Ignore_White_Spaces;
Xml_Parser.Ignore_Empty_Lines := Handler.Ignore_Empty_Lines;
Sax.Readers.Reader (Xml_Parser).Parse (Input);
end Parse;
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Output_Stream'Class);
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Output_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
-- ------------------------------
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
-- ------------------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Close_Current (Stream);
Stream.Write (Value);
end Write_String;
-- ------------------------------
-- Start a new XML object.
-- ------------------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Close_Start := True;
Stream.Write ('<');
Stream.Write (Name);
end Start_Entity;
-- ------------------------------
-- Terminates the current XML object.
-- ------------------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end End_Entity;
-- ------------------------------
-- Write a XML name/value attribute.
-- ------------------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Stream.Write (' ');
Stream.Write (Name);
Stream.Write ("=""");
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ('"');
end Write_Attribute;
-- ------------------------------
-- Write a XML name/value entity (see Write_Attribute).
-- ------------------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write (Name);
Stream.Write ('>');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end Write_Entity;
-- ------------------------------
-- Starts a XML array.
-- ------------------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
begin
null;
end Start_Array;
-- ------------------------------
-- Terminates a XML array.
-- ------------------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
null;
end End_Array;
end Util.Serialize.IO.XML;
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- 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 Unicode;
with Unicode.CES.Utf8;
with Util.Log.Loggers;
package body Util.Serialize.IO.XML is
use Util.Log;
use Sax.Readers;
use Sax.Exceptions;
use Sax.Locators;
use Sax.Attributes;
use Unicode;
use Unicode.CES;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.XML");
-- ------------------------------
-- Warning
-- ------------------------------
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Warn ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Warning;
-- ------------------------------
-- Error
-- ------------------------------
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Warnings (Off, Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Error;
-- ------------------------------
-- Fatal_Error
-- ------------------------------
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class) is
pragma Unreferenced (Handler);
begin
Log.Error ("{0}: {1}", To_String (Get_Locator (Except)), Get_Message (Except));
end Fatal_Error;
-- ------------------------------
-- Set_Document_Locator
-- ------------------------------
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator) is
begin
Handler.Locator := Loc;
end Set_Document_Locator;
-- ------------------------------
-- Start_Document
-- ------------------------------
overriding
procedure Start_Document (Handler : in out Xhtml_Reader) is
begin
null;
end Start_Document;
-- ------------------------------
-- End_Document
-- ------------------------------
overriding
procedure End_Document (Handler : in out Xhtml_Reader) is
begin
null;
end End_Document;
-- ------------------------------
-- Start_Prefix_Mapping
-- ------------------------------
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence) is
begin
null;
end Start_Prefix_Mapping;
-- ------------------------------
-- End_Prefix_Mapping
-- ------------------------------
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence) is
begin
null;
end End_Prefix_Mapping;
-- ------------------------------
-- Start_Element
-- ------------------------------
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class) is
pragma Unreferenced (Namespace_URI, Qname);
Attr_Count : Natural;
begin
-- Handler.Line.Line := Sax.Locators.Get_Line_Number (Handler.Locator);
-- Handler.Line.Column := Sax.Locators.Get_Column_Number (Handler.Locator);
Log.Debug ("Start object {0}", Local_Name);
Handler.Handler.Start_Object (Local_Name);
Attr_Count := Get_Length (Atts);
for I in 0 .. Attr_Count - 1 loop
declare
Name : constant String := Get_Qname (Atts, I);
Value : constant String := Get_Value (Atts, I);
begin
Handler.Handler.Set_Member (Name => Name,
Value => Util.Beans.Objects.To_Object (Value),
Attribute => True);
end;
end loop;
end Start_Element;
-- ------------------------------
-- End_Element
-- ------------------------------
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "") is
pragma Unreferenced (Namespace_URI, Qname);
begin
Handler.Handler.Finish_Object (Local_Name);
if Length (Handler.Text) > 0 then
Log.Debug ("Close object {0} -> {1}", Local_Name, To_String (Handler.Text));
Handler.Handler.Set_Member (Local_Name, Util.Beans.Objects.To_Object (Handler.Text));
Set_Unbounded_String (Handler.Text, "");
else
Log.Debug ("Close object {0}", Local_Name);
end if;
end End_Element;
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence) is
begin
Append (Handler.Text, Content);
end Collect_Text;
-- ------------------------------
-- Characters
-- ------------------------------
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
Collect_Text (Handler, Ch);
end Characters;
-- ------------------------------
-- Ignorable_Whitespace
-- ------------------------------
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence) is
begin
if not Handler.Ignore_White_Spaces then
Collect_Text (Handler, Ch);
end if;
end Ignorable_Whitespace;
-- ------------------------------
-- Processing_Instruction
-- ------------------------------
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence) is
pragma Unreferenced (Handler);
begin
Log.Error ("Processing instruction: {0}: {1}", Target, Data);
end Processing_Instruction;
-- ------------------------------
-- Skipped_Entity
-- ------------------------------
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence) is
pragma Unmodified (Handler);
begin
null;
end Skipped_Entity;
-- ------------------------------
-- Start_Cdata
-- ------------------------------
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("Start CDATA");
end Start_Cdata;
-- ------------------------------
-- End_Cdata
-- ------------------------------
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader) is
pragma Unmodified (Handler);
begin
Log.Info ("End CDATA");
end End_Cdata;
-- ------------------------------
-- Resolve_Entity
-- ------------------------------
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access is
pragma Unreferenced (Handler);
begin
Log.Error ("Cannot resolve entity {0} - {1}", Public_Id, System_Id);
return null;
end Resolve_Entity;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "") is
begin
null;
end Start_DTD;
-- ------------------------------
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
-- ------------------------------
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_White_Spaces := Value;
end Set_Ignore_White_Spaces;
-- ------------------------------
-- Set the XHTML reader to ignore empty lines.
-- ------------------------------
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean) is
begin
Reader.Ignore_Empty_Lines := Value;
end Set_Ignore_Empty_Lines;
-- ------------------------------
-- Parse an XML stream, and calls the appropriate SAX callbacks for each
-- event.
-- This is not re-entrant: you can not call Parse with the same Parser
-- argument in one of the SAX callbacks. This has undefined behavior.
-- ------------------------------
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
type String_Access is access all String (1 .. 32);
type Stream_Input is new Input_Sources.Input_Source with record
Index : Natural;
Last : Natural;
Encoding : Unicode.CES.Encoding_Scheme;
Buffer : String_Access;
end record;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char);
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean;
procedure Fill (From : in out Stream_Input'Class);
procedure Fill (From : in out Stream_Input'Class) is
begin
-- Move to the buffer start
if From.Last > From.Index and From.Index > From.Buffer'First then
From.Buffer (From.Buffer'First .. From.Last - 1 - From.Index + From.Buffer'First) :=
From.Buffer (From.Index .. From.Last - 1);
From.Last := From.Last - From.Index + From.Buffer'First;
From.Index := From.Buffer'First;
end if;
if From.Index > From.Last then
From.Index := From.Buffer'First;
end if;
begin
loop
Stream.Read (From.Buffer (From.Last));
From.Last := From.Last + 1;
exit when From.Last > From.Buffer'Last;
end loop;
exception
when others =>
null;
end;
end Fill;
-- Return the next character in the string.
procedure Next_Char (From : in out Stream_Input;
C : out Unicode.Unicode_Char) is
begin
if From.Index + 6 >= From.Last then
Fill (From);
end if;
From.Encoding.Read (From.Buffer.all, From.Index, C);
end Next_Char;
-- True if From is past the last character in the string.
function Eof (From : in Stream_Input) return Boolean is
begin
if From.Index < From.Last then
return False;
end if;
return Stream.Is_Eof;
end Eof;
Input : Stream_Input;
Xml_Parser : Xhtml_Reader;
Buf : aliased String (1 .. 32);
begin
Input.Buffer := Buf'Access;
Input.Index := 2;
Input.Last := 1;
Input.Set_Encoding (Unicode.CES.Utf8.Utf8_Encoding);
Input.Encoding := Unicode.CES.Utf8.Utf8_Encoding;
Xml_Parser.Handler := Handler'Unchecked_Access;
Xml_Parser.Ignore_White_Spaces := Handler.Ignore_White_Spaces;
Xml_Parser.Ignore_Empty_Lines := Handler.Ignore_Empty_Lines;
Sax.Readers.Reader (Xml_Parser).Parse (Input);
end Parse;
-- Close the current XML entity if an entity was started
procedure Close_Current (Stream : in out Output_Stream'Class);
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Output_Stream'Class) is
begin
if Stream.Close_Start then
Stream.Write ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
-- ------------------------------
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
-- ------------------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Close_Current (Stream);
Stream.Write (Value);
end Write_String;
-- ------------------------------
-- Start a new XML object.
-- ------------------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Close_Start := True;
Stream.Write ('<');
Stream.Write (Name);
end Start_Entity;
-- ------------------------------
-- Terminates the current XML object.
-- ------------------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
begin
Close_Current (Stream);
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end End_Entity;
-- ------------------------------
-- Write a XML name/value attribute.
-- ------------------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Stream.Write (' ');
Stream.Write (Name);
Stream.Write ("=""");
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ('"');
end Write_Attribute;
-- ------------------------------
-- Write a XML name/value entity (see Write_Attribute).
-- ------------------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
Close_Current (Stream);
Stream.Write ('<');
Stream.Write (Name);
Stream.Write ('>');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
null;
when TYPE_BOOLEAN =>
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
when others =>
Stream.Write_String (Util.Beans.Objects.To_String (Value));
end case;
Stream.Write ("</");
Stream.Write (Name);
Stream.Write ('>');
end Write_Entity;
-- ------------------------------
-- Starts a XML array.
-- ------------------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
begin
null;
end Start_Array;
-- ------------------------------
-- Terminates a XML array.
-- ------------------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
null;
end End_Array;
end Util.Serialize.IO.XML;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
|
1aeac022f5a25ab65e3e6b74c8217364dc254b4d
|
test/FrontendAda/element_copy.adb
|
test/FrontendAda/element_copy.adb
|
-- RUN: %llvmgcc -S -O2 %s -I%p/Support -o - | grep 105 | count 2
package body Element_Copy is
function F return VariableSizedField is
X : VariableSizedField;
begin
return X;
end;
end;
|
-- RUN: %llvmgcc -S -O2 %s -I%p/Support -o - | grep 6899714
package body Element_Copy is
function F return VariableSizedField is
X : VariableSizedField;
begin
return X;
end;
end;
|
Adjust this test for recent sroa improvements.
|
Adjust this test for recent sroa improvements.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@66791 91177308-0d34-0410-b5e6-96231b3b80d8
|
Ada
|
bsd-2-clause
|
chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm
|
a3d2e5dee9e47295e56bd58bd97aa550aefc9b86
|
mat/src/mat-expressions.ads
|
mat/src/mat-expressions.ads
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME,
N_CONDITION, N_THREAD);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- 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.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME, N_EVENT,
N_CONDITION, N_THREAD);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when N_EVENT =>
Min_Event : MAT.Events.Targets.Event_Id_Type;
Max_Event : MAT.Events.Targets.Event_Id_Type;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
Define the N_EVENT expression node type to describe a condition on the event ID
|
Define the N_EVENT expression node type to describe a condition on the event ID
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
8533921bad7a989aef8f076701a49378e0db6bf7
|
samples/render.adb
|
samples/render.adb
|
-----------------------------------------------------------------------
-- render -- XHTML Rendering example
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with GNAT.Command_Line;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with EL.Objects;
-- This example reads an XHTML file and renders the result.
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Fixed;
use ASF;
use EL.Objects;
Factory : ASF.Applications.Main.Application_Factory;
App : Applications.Main.Application;
Conf : Applications.Config;
begin
Conf.Set ("view.ignore_white_spaces", "false");
Conf.Set ("view.escape_unknown_tags", "false");
Conf.Set ("view.ignore_empty_lines", "true");
App.Initialize (Conf, Factory);
loop
case Getopt ("D:") is
when 'D' =>
declare
Value : constant String := Parameter;
Pos : constant Natural := Index (Value, "=");
begin
if Pos > 0 then
App.Set_Global (Name => Value (1 .. Pos - 1),
Value => To_Object (Value (Pos + 1 .. Value'Last)));
else
App.Set_Global (Name => Value (1 .. Pos - 1),
Value => To_Object(True));
end if;
end;
when others =>
exit;
end case;
end loop;
declare
View_Name : constant String := Get_Argument;
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Req.Set_Path_Info (View_Name);
App.Dispatch (Page => View_Name,
Request => Req,
Response => Reply);
Reply.Read_Content (Content);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content));
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'");
end;
end Render;
|
-----------------------------------------------------------------------
-- render -- XHTML Rendering example
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
with GNAT.Command_Line;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with EL.Objects;
-- This example reads an XHTML file and renders the result.
procedure Render is
use GNAT.Command_Line;
use Ada.Strings.Fixed;
use ASF;
use EL.Objects;
Factory : ASF.Applications.Main.Application_Factory;
App : Applications.Main.Application;
Conf : Applications.Config;
begin
Conf.Set ("view.ignore_white_spaces", "false");
Conf.Set ("view.escape_unknown_tags", "false");
Conf.Set ("view.ignore_empty_lines", "true");
App.Initialize (Conf, Factory);
loop
case Getopt ("D:") is
when 'D' =>
declare
Value : constant String := Parameter;
Pos : constant Natural := Index (Value, "=");
begin
if Pos > 0 then
App.Set_Global (Name => Value (Value'First .. Pos - 1),
Value => To_Object (Value (Pos + 1 .. Value'Last)));
else
App.Set_Global (Name => Value (Value'First .. Pos - 1),
Value => To_Object (True));
end if;
end;
when others =>
exit;
end case;
end loop;
declare
View_Name : constant String := Get_Argument;
Pos : constant Natural := Index (View_Name, ".");
Req : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
if View_Name = "" or Pos = 0 then
Ada.Text_IO.Put_Line ("Usage: render [-DNAME=VALUE ] file");
Ada.Text_IO.Put_Line ("Example: render -DcontextPath=/test samples/web/ajax.xhtml");
return;
end if;
Req.Set_Path_Info (View_Name (View_Name'First .. Pos - 1));
App.Dispatch (Page => View_Name (View_Name'First .. Pos - 1),
Request => Req,
Response => Reply);
Reply.Read_Content (Content);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Content));
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'");
end;
end Render;
|
Fix usage of render example
|
Fix usage of render example
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
024bf9ca67b4bd5cd36e8f6b466c69a254fbc945
|
src/ado-queries.adb
|
src/ado-queries.adb
|
-----------------------------------------------------------------------
-- ado-queries -- Database Queries
-- 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.Unchecked_Deallocation;
with ADO.Queries.Loaders;
package body ADO.Queries is
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query is represented by the <tt>sql</tt> XML entry.
-- ------------------------------
procedure Set_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := False;
end Set_Query;
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query count is represented by the <tt>sql-count</tt> XML entry.
-- ------------------------------
procedure Set_Count_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := True;
end Set_Count_Query;
procedure Set_Query (Into : in out Context;
Name : in String) is
begin
Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name);
end Set_Query;
-- ------------------------------
-- Set the query to execute as SQL statement.
-- ------------------------------
procedure Set_SQL (Into : in out Context;
SQL : in String) is
begin
ADO.SQL.Clear (Into.SQL);
ADO.SQL.Append (Into.SQL, SQL);
end Set_SQL;
-- ------------------------------
-- Set the limit for the SQL query.
-- ------------------------------
procedure Set_Limit (Into : in out Context;
First : in Natural;
Last : in Natural) is
begin
Into.First := First;
Into.Last := Last;
end Set_Limit;
-- ------------------------------
-- Get the first row index.
-- ------------------------------
function Get_First_Row_Index (From : in Context) return Natural is
begin
return From.First;
end Get_First_Row_Index;
-- ------------------------------
-- Get the last row index.
-- ------------------------------
function Get_Last_Row_Index (From : in Context) return Natural is
begin
return From.Last;
end Get_Last_Row_Index;
-- ------------------------------
-- Get the maximum number of rows that the SQL query can return.
-- This operation uses the <b>sql-count</b> query.
-- ------------------------------
function Get_Max_Row_Count (From : in Context) return Natural is
begin
return From.Max_Row_Count;
end Get_Max_Row_Count;
-- ------------------------------
-- Get the SQL query that correspond to the query context.
-- ------------------------------
function Get_SQL (From : in Context;
Manager : in Query_Manager'Class) return String is
begin
if From.Query_Def = null then
return ADO.SQL.To_String (From.SQL);
else
return Get_SQL (From.Query_Def, Manager, From.Is_Count);
end if;
end Get_SQL;
-- ------------------------------
-- Find the query with the given name.
-- Returns the query definition that matches the name or null if there is none
-- ------------------------------
function Find_Query (File : in Query_File_Info;
Name : in String) return Query_Definition_Access is
Query : Query_Definition_Access := File.File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
return null;
end Find_Query;
function Get_SQL (From : in Query_Definition_Access;
Manager : in Query_Manager;
Use_Count : in Boolean) return String is
Query : Query_Info_Ref.Ref;
begin
ADO.Queries.Loaders.Read_Query (Manager, From);
Query := Manager.Queries (From.Query).Get;
if Query.Is_Null then
return "";
end if;
if Use_Count then
if Length (Query.Value.Count_Query (Manager.Driver).SQL) > 0 then
return To_String (Query.Value.Count_Query (Manager.Driver).SQL);
else
return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
elsif Length (Query.Value.Main_Query (Manager.Driver).SQL) > 0 then
return To_String (Query.Value.Main_Query (Manager.Driver).SQL);
else
return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
end Get_SQL;
overriding
procedure Finalize (Manager : in out Query_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => File_Table,
Name => File_Table_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Query_Table,
Name => Query_Table_Access);
begin
Free (Manager.Queries);
Free (Manager.Files);
end Finalize;
end ADO.Queries;
|
-----------------------------------------------------------------------
-- ado-queries -- Database Queries
-- 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.Unchecked_Deallocation;
with ADO.Queries.Loaders;
package body ADO.Queries is
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query is represented by the <tt>sql</tt> XML entry.
-- ------------------------------
procedure Set_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := False;
end Set_Query;
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query count is represented by the <tt>sql-count</tt> XML entry.
-- ------------------------------
procedure Set_Count_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := True;
end Set_Count_Query;
procedure Set_Query (Into : in out Context;
Name : in String) is
begin
Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name);
end Set_Query;
-- ------------------------------
-- Set the query to execute as SQL statement.
-- ------------------------------
procedure Set_SQL (Into : in out Context;
SQL : in String) is
begin
ADO.SQL.Clear (Into.SQL);
ADO.SQL.Append (Into.SQL, SQL);
end Set_SQL;
-- ------------------------------
-- Set the limit for the SQL query.
-- ------------------------------
procedure Set_Limit (Into : in out Context;
First : in Natural;
Last : in Natural) is
begin
Into.First := First;
Into.Last := Last;
end Set_Limit;
-- ------------------------------
-- Get the first row index.
-- ------------------------------
function Get_First_Row_Index (From : in Context) return Natural is
begin
return From.First;
end Get_First_Row_Index;
-- ------------------------------
-- Get the last row index.
-- ------------------------------
function Get_Last_Row_Index (From : in Context) return Natural is
begin
return From.Last;
end Get_Last_Row_Index;
-- ------------------------------
-- Get the maximum number of rows that the SQL query can return.
-- This operation uses the <b>sql-count</b> query.
-- ------------------------------
function Get_Max_Row_Count (From : in Context) return Natural is
begin
return From.Max_Row_Count;
end Get_Max_Row_Count;
-- ------------------------------
-- Get the SQL query that correspond to the query context.
-- ------------------------------
function Get_SQL (From : in Context;
Manager : in Query_Manager'Class) return String is
begin
if From.Query_Def = null then
return ADO.SQL.To_String (From.SQL);
else
return Get_SQL (From.Query_Def, Manager, From.Is_Count);
end if;
end Get_SQL;
-- ------------------------------
-- Find the query with the given name.
-- Returns the query definition that matches the name or null if there is none
-- ------------------------------
function Find_Query (File : in Query_File_Info;
Name : in String) return Query_Definition_Access is
Query : Query_Definition_Access := File.File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
return null;
end Find_Query;
function Get_SQL (From : in Query_Definition_Access;
Manager : in Query_Manager;
Use_Count : in Boolean) return String is
Query : Query_Info_Ref.Ref;
begin
ADO.Queries.Loaders.Read_Query (Manager, From);
Query := Manager.Queries (From.Query);
if Query.Is_Null then
return "";
end if;
if Use_Count then
if Length (Query.Value.Count_Query (Manager.Driver).SQL) > 0 then
return To_String (Query.Value.Count_Query (Manager.Driver).SQL);
else
return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
elsif Length (Query.Value.Main_Query (Manager.Driver).SQL) > 0 then
return To_String (Query.Value.Main_Query (Manager.Driver).SQL);
else
return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
end Get_SQL;
overriding
procedure Finalize (Manager : in out Query_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => File_Table,
Name => File_Table_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Query_Table,
Name => Query_Table_Access);
begin
Free (Manager.Queries);
Free (Manager.Files);
end Finalize;
end ADO.Queries;
|
Update to use the simple reference
|
Update to use the simple reference
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
78ac990bead0d8bfc89d6e32afa180187d4e97a1
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Compare two files on their name and directory.
-- ------------------------------
function "<" (Left, Right : in File_Type) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left = NO_FILE then
return False;
elsif Right = NO_FILE then
return True;
elsif Left.Dir = Right.Dir then
return Left.Name < Right.Name;
elsif Left.Dir = NO_DIRECTORY then
return True;
elsif Right.Dir = NO_DIRECTORY then
return False;
else
return Left.Dir.Path < Right.Dir.Path;
end if;
end "<";
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
use Ada.Strings.Unbounded;
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
else
Result.Path := To_Unbounded_String (Name);
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Return true if the file is a new file.
-- ------------------------------
function Is_New (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
return Element.Id = NO_IDENTIFIER;
end Is_New;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- 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) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- 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) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Return the file size.
-- ------------------------------
function Get_Size (Element : in File_Type) return File_Size is
begin
return Element.Size;
end Get_Size;
-- ------------------------------
-- Return the file modification date.
-- ------------------------------
function Get_Date (Element : in File_Type) return Ada.Calendar.Time is
begin
return Element.Date;
end Get_Date;
-- ------------------------------
-- Return the user uid.
-- ------------------------------
function Get_User (Element : in File_Type) return Uid_Type is
begin
return Element.User;
end Get_User;
-- ------------------------------
-- Return the group gid.
-- ------------------------------
function Get_Group (Element : in File_Type) return Gid_Type is
begin
return Element.Group;
end Get_Group;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- 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 is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- 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 is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- 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 is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Execute the Process procedure on each directory found in the container.
-- ------------------------------
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is
Iter : Directory_Vectors.Cursor := Container.Dirs.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Process (Directory_Vectors.Element (Iter));
Directory_Vectors.Next (Iter);
end loop;
end Each_Directory;
-- ------------------------------
-- Execute the Process procedure on each file found in the container.
-- ------------------------------
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type)) is
Iter : File_Vectors.Cursor := Container.Files.First;
begin
while File_Vectors.Has_Element (Iter) loop
Process (File_Vectors.Element (Iter));
File_Vectors.Next (Iter);
end loop;
end Each_File;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Compare two files on their name and directory.
-- ------------------------------
function "<" (Left, Right : in File_Type) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left = NO_FILE then
return False;
elsif Right = NO_FILE then
return True;
elsif Left.Dir = Right.Dir then
return Left.Name < Right.Name;
elsif Left.Dir = NO_DIRECTORY then
return True;
elsif Right.Dir = NO_DIRECTORY then
return False;
else
return Left.Dir.Path < Right.Dir.Path;
end if;
end "<";
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
use Ada.Strings.Unbounded;
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
else
Result.Path := To_Unbounded_String (Name);
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Return true if the file is a new file.
-- ------------------------------
function Is_New (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
return Element.Id = NO_IDENTIFIER;
end Is_New;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- 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) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- 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) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Return the file size.
-- ------------------------------
function Get_Size (Element : in File_Type) return File_Size is
begin
return Element.Size;
end Get_Size;
-- ------------------------------
-- Return the file modification date.
-- ------------------------------
function Get_Date (Element : in File_Type) return Ada.Calendar.Time is
begin
return Element.Date;
end Get_Date;
-- ------------------------------
-- Return the user uid.
-- ------------------------------
function Get_User (Element : in File_Type) return Uid_Type is
begin
return Element.User;
end Get_User;
-- ------------------------------
-- Return the group gid.
-- ------------------------------
function Get_Group (Element : in File_Type) return Gid_Type is
begin
return Element.Group;
end Get_Group;
-- ------------------------------
-- Return the file unix mode.
-- ------------------------------
function Get_Mode (Element : in File_Type) return File_Mode is
begin
return Element.Mode;
end Get_Mode;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- 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 is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- 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 is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- 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 is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Execute the Process procedure on each directory found in the container.
-- ------------------------------
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is
Iter : Directory_Vectors.Cursor := Container.Dirs.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Process (Directory_Vectors.Element (Iter));
Directory_Vectors.Next (Iter);
end loop;
end Each_Directory;
-- ------------------------------
-- Execute the Process procedure on each file found in the container.
-- ------------------------------
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type)) is
Iter : File_Vectors.Cursor := Container.Files.First;
begin
while File_Vectors.Has_Element (Iter) loop
Process (File_Vectors.Element (Iter));
File_Vectors.Next (Iter);
end loop;
end Each_File;
end Babel.Files;
|
Implement the Get_Mode operation
|
Implement the Get_Mode operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
ff352529fb81e1a4333be8d97ba74bbe48d5a1e8
|
mat/src/memory/mat-memory-targets.ads
|
mat/src/memory/mat-memory-targets.ads
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Frames;
with Util.Events;
with MAT.Memory.Events;
with MAT.Readers;
with Ada.Containers.Ordered_Maps;
package MAT.Memory.Targets is
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
type Size_Info_Type is record
Count : Natural;
end record;
use type MAT.Types.Target_Size;
package Size_Info_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size,
Element_Type => Size_Info_Type);
subtype Size_Info_Map is Size_Info_Maps.Map;
subtype Size_Info_Cursor is Size_Info_Maps.Cursor;
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Memory : in out Target_Memory;
Sizes : in out Size_Info_Map);
private
protected type Memory_Allocator is
-- 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);
-- 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);
-- 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);
-- 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);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out Size_Info_Map);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Reader : MAT.Readers.Reader_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory clients - Client info related to its memory
-- 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 Util.Events;
with MAT.Frames;
with MAT.Readers;
with MAT.Memory.Events;
with MAT.Memory.Tools;
package MAT.Memory.Targets is
type Target_Memory is tagged limited private;
type Client_Memory_Ref is access all Target_Memory;
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
-- 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);
private
protected type Memory_Allocator is
-- 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);
-- 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);
-- 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);
-- 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);
-- Collect the information about memory slot sizes allocated by the application.
procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root;
end Memory_Allocator;
type Target_Memory is tagged limited record
Reader : MAT.Readers.Reader_Access;
Memory : Memory_Allocator;
end record;
end MAT.Memory.Targets;
|
Use the MAT.Memory.Tools package for the sizes map
|
Use the MAT.Memory.Tools package for the sizes map
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
02b4f42369546d53b5f3bf40aef7dd1eb028624d
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Send_Invitation (Bean);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Send_Invitation (Bean);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
Fix compilation with gcc 4.6 that does not support all Ada 2012 features
|
Fix compilation with gcc 4.6 that does not support all Ada 2012 features
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
73cb560b38192193b8187cb42c7c08c51a3ac777
|
regtests/util-dates-tests.adb
|
regtests/util-dates-tests.adb
|
-----------------------------------------------------------------------
-- util-dates-tests - Test for dates
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Dates.ISO8601;
package body Util.Dates.Tests is
package Caller is new Util.Test_Caller (Test, "Dates");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Image",
Test_ISO8601_Image'Access);
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value",
Test_ISO8601_Value'Access);
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value (Errors)",
Test_ISO8601_Error'Access);
end Add_Tests;
-- ------------------------------
-- Test converting a date in ISO8601.
-- ------------------------------
procedure Test_ISO8601_Image (T : in out Test) is
T1 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (1980, 1, 2, 10, 30, 23);
begin
Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1),
"Invalid Image");
Util.Tests.Assert_Equals (T, "1980", ISO8601.Image (T1, ISO8601.YEAR),
"Invalid Image (YEAR precision)");
Util.Tests.Assert_Equals (T, "1980-01", ISO8601.Image (T1, ISO8601.MONTH),
"Invalid Image (MONTH precision)");
Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1, ISO8601.DAY),
"Invalid Image (DAY precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10", ISO8601.Image (T1, ISO8601.HOUR),
"Invalid Image (DAY precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10:30", ISO8601.Image (T1, ISO8601.MINUTE),
"Invalid Image (MINUTE precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10:30:23", ISO8601.Image (T1, ISO8601.SECOND),
"Invalid Image (SECOND precision)");
end Test_ISO8601_Image;
-- ------------------------------
-- Test converting a string in ISO8601 into a date.
-- ------------------------------
procedure Test_ISO8601_Value (T : in out Test) is
Date : Ada.Calendar.Time;
begin
Date := ISO8601.Value ("1980");
Util.Tests.Assert_Equals (T, "1980-01-01", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-02");
Util.Tests.Assert_Equals (T, "1980-02", ISO8601.Image (Date, ISO8601.MONTH));
Date := ISO8601.Value ("1980-03-04");
Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-03-04");
Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-12-31");
Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date));
Date := ISO8601.Value ("19801231");
Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-12-31T11:23");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23", ISO8601.Image (Date, ISO8601.MINUTE));
Date := ISO8601.Value ("1980-12-31T11:23:34");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34", ISO8601.Image (Date, ISO8601.SECOND));
Date := ISO8601.Value ("1980-12-31T11:23:34.123");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34.123+00:00",
ISO8601.Image (Date, ISO8601.SUBSECOND));
Date := ISO8601.Value ("1980-12-31T11:23:34.123+04:30");
-- The date was normalized in GMT
Util.Tests.Assert_Equals (T, "1980-12-31T06:53:34.123+00:00",
ISO8601.Image (Date, ISO8601.SUBSECOND));
end Test_ISO8601_Value;
-- ------------------------------
-- Test value convertion errors.
-- ------------------------------
procedure Test_ISO8601_Error (T : in out Test) is
procedure Check (Date : in String);
procedure Check (Date : in String) is
begin
declare
Unused : constant Ada.Calendar.Time := ISO8601.Value (Date);
begin
T.Fail ("No exception raised for " & Date);
end;
exception
when Constraint_Error =>
null;
end Check;
begin
Check ("");
Check ("1980-");
Check ("1980:02:03");
Check ("1980-02-03u33:33");
Check ("1980-02-03u33");
Check ("1980-13-44");
Check ("1980-12-00");
Check ("1980-12-03T25:34");
Check ("1980-12-03T10x34");
Check ("1980-12-03T10:34p");
Check ("1980-12-31T11:23:34123");
Check ("1980-12-31T11:23:34,1");
Check ("1980-12-31T11:23:34,12");
Check ("1980-12-31T11:23:34x123");
Check ("1980-12-31T11:23:34.1234");
Check ("1980-12-31T11:23:34Zp");
Check ("1980-12-31T11:23:34+2");
Check ("1980-12-31T11:23:34+23x");
Check ("1980-12-31T11:23:34+99");
Check ("1980-12-31T11:23:34+10:0");
Check ("1980-12-31T11:23:34+10:03x");
end Test_ISO8601_Error;
end Util.Dates.Tests;
|
-----------------------------------------------------------------------
-- util-dates-tests - Test for dates
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Dates.ISO8601;
package body Util.Dates.Tests is
package Caller is new Util.Test_Caller (Test, "Dates");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Image",
Test_ISO8601_Image'Access);
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value",
Test_ISO8601_Value'Access);
Caller.Add_Test (Suite, "Test Util.Dates.ISO8601.Value (Errors)",
Test_ISO8601_Error'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Is_Same_Day",
Test_Is_Same_Day'Access);
end Add_Tests;
-- ------------------------------
-- Test converting a date in ISO8601.
-- ------------------------------
procedure Test_ISO8601_Image (T : in out Test) is
T1 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (1980, 1, 2, 10, 30, 23);
begin
Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1),
"Invalid Image");
Util.Tests.Assert_Equals (T, "1980", ISO8601.Image (T1, ISO8601.YEAR),
"Invalid Image (YEAR precision)");
Util.Tests.Assert_Equals (T, "1980-01", ISO8601.Image (T1, ISO8601.MONTH),
"Invalid Image (MONTH precision)");
Util.Tests.Assert_Equals (T, "1980-01-02", ISO8601.Image (T1, ISO8601.DAY),
"Invalid Image (DAY precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10", ISO8601.Image (T1, ISO8601.HOUR),
"Invalid Image (DAY precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10:30", ISO8601.Image (T1, ISO8601.MINUTE),
"Invalid Image (MINUTE precision)");
Util.Tests.Assert_Equals (T, "1980-01-02T10:30:23", ISO8601.Image (T1, ISO8601.SECOND),
"Invalid Image (SECOND precision)");
end Test_ISO8601_Image;
-- ------------------------------
-- Test converting a string in ISO8601 into a date.
-- ------------------------------
procedure Test_ISO8601_Value (T : in out Test) is
Date : Ada.Calendar.Time;
begin
Date := ISO8601.Value ("1980");
Util.Tests.Assert_Equals (T, "1980-01-01", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-02");
Util.Tests.Assert_Equals (T, "1980-02", ISO8601.Image (Date, ISO8601.MONTH));
Date := ISO8601.Value ("1980-03-04");
Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-03-04");
Util.Tests.Assert_Equals (T, "1980-03-04", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-12-31");
Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date));
Date := ISO8601.Value ("19801231");
Util.Tests.Assert_Equals (T, "1980-12-31", ISO8601.Image (Date));
Date := ISO8601.Value ("1980-12-31T11:23");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23", ISO8601.Image (Date, ISO8601.MINUTE));
Date := ISO8601.Value ("1980-12-31T11:23:34");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34", ISO8601.Image (Date, ISO8601.SECOND));
Date := ISO8601.Value ("1980-12-31T11:23:34.123");
Util.Tests.Assert_Equals (T, "1980-12-31T11:23:34.123+00:00",
ISO8601.Image (Date, ISO8601.SUBSECOND));
Date := ISO8601.Value ("1980-12-31T11:23:34.123+04:30");
-- The date was normalized in GMT
Util.Tests.Assert_Equals (T, "1980-12-31T06:53:34.123+00:00",
ISO8601.Image (Date, ISO8601.SUBSECOND));
end Test_ISO8601_Value;
-- ------------------------------
-- Test value convertion errors.
-- ------------------------------
procedure Test_ISO8601_Error (T : in out Test) is
procedure Check (Date : in String);
procedure Check (Date : in String) is
begin
declare
Unused : constant Ada.Calendar.Time := ISO8601.Value (Date);
begin
T.Fail ("No exception raised for " & Date);
end;
exception
when Constraint_Error =>
null;
end Check;
begin
Check ("");
Check ("1980-");
Check ("1980:02:03");
Check ("1980-02-03u33:33");
Check ("1980-02-03u33");
Check ("1980-13-44");
Check ("1980-12-00");
Check ("1980-12-03T25:34");
Check ("1980-12-03T10x34");
Check ("1980-12-03T10:34p");
Check ("1980-12-31T11:23:34123");
Check ("1980-12-31T11:23:34,1");
Check ("1980-12-31T11:23:34,12");
Check ("1980-12-31T11:23:34x123");
Check ("1980-12-31T11:23:34.1234");
Check ("1980-12-31T11:23:34Zp");
Check ("1980-12-31T11:23:34+2");
Check ("1980-12-31T11:23:34+23x");
Check ("1980-12-31T11:23:34+99");
Check ("1980-12-31T11:23:34+10:0");
Check ("1980-12-31T11:23:34+10:03x");
end Test_ISO8601_Error;
-- ------------------------------
-- Test Is_Same_Day operation.
-- ------------------------------
procedure Test_Is_Same_Day (T : in out Test) is
procedure Check (D1, D2 : in String;
Same_Day : in Boolean);
procedure Check (D1, D2 : in String;
Same_Day : in Boolean) is
T1 : constant Ada.Calendar.Time := ISO8601.Value (D1);
T2 : constant Ada.Calendar.Time := ISO8601.Value (D2);
begin
T.Assert (Same_Day = Is_Same_Day (T1, T2), "Invalid Is_Same_Day for " & D1 & " " & D2);
T.Assert (Same_Day = Is_Same_Day (T2, T1), "Invalid Is_Same_Day for " & D2 & " " & D1);
end Check;
begin
Check ("1980-12-31T11:23:34.123", "1980-12-31T10:23:34.123", True);
Check ("1980-12-31T11:23:34.123", "1980-12-30T10:23:34.123", False);
Check ("1980-12-31T00:00:00", "1980-12-31T23:59:59", True);
end Test_Is_Same_Day;
end Util.Dates.Tests;
|
Add new test for Is_Same_Day operation
|
Add new test for Is_Same_Day operation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
11298372d3d343316e2b2755eb51daf261284cfe
|
lua-userdata.adb
|
lua-userdata.adb
|
-- Lua.Userdata
-- Adding Ada objects to Lua environment
-- Copyright (c) 2015, James Humphry - see LICENSE.md for terms
with System.Address_To_Access_Conversions;
with Interfaces, Interfaces.C, Interfaces.C.Strings;
use Interfaces;
with Lua.Internal, Lua.AuxInternal;
package body Lua.Userdata is
use type Ada.Tags.Tag;
use type C.int;
--
-- *** Conversions between C types and Ada types
--
package Address_To_Ada_Userdata is
new System.Address_To_Access_Conversions(Object => Ada_Userdata);
procedure Push (L : in Lua_State'Class; D : not null access T) is
UserData_Address : System.Address
:= Internal.lua_newuserdata(L.L, Ada_Userdata'Size);
UserData_Access : access Ada_Userdata
:= Address_To_Ada_Userdata.To_Pointer(UserData_Address);
Has_Metatable : Boolean;
begin
UserData_Access.all.Tag := T'Tag;
UserData_Access.all.Data := D;
Has_Metatable := GetMetaTable(L);
if Has_Metatable then
Setmetatable(L, -2);
end if;
end Push;
function ToUserdata (L : in Lua_State'Class; index : in Integer)
return not null access T
is
UserData_Address : System.Address
:= Internal.lua_touserdata(L.L, C.int(index));
UserData_Access : access Ada_Userdata
:= Address_To_Ada_Userdata.To_Pointer(UserData_Address);
begin
if UserData_Access = null then
raise Program_Error with "Attempting to access non-userdata as userdata";
elsif UserData_Access.Tag /= T'Tag then
raise Program_Error with "Attempting invalid userdata type conversion";
end if;
return UserData_Access.Data;
end ToUserdata;
procedure NewMetaTable (L : in Lua_State'Class;
Set_Indexable : Boolean := True) is
tname : C.Strings.chars_ptr
:= C.Strings.New_String("Ada_UserData:" & T'External_Tag);
Result : C.int;
begin
Result := AuxInternal.luaL_newmetatable(L.L, tname);
C.Strings.Free(tname);
if Result = 0 then
raise Program_Error with "Metatable could not be created or already exists";
elsif Set_Indexable then
-- Setting the metatables __index field to itself so any unidentified
-- operations of the form object:operation() will be looked up in the
-- metatable itself
L.PushValue(-1);
L.SetField(-2, "__index");
end if;
end NewMetaTable;
function GetMetaTable (L : in Lua_State'Class) return Boolean is
tname : C.Strings.chars_ptr
:= C.Strings.New_String("Ada_UserData:" & T'External_Tag);
Result : C.int;
begin
Result := Internal.lua_getfield(L.L, C.int(RegistryIndex), tname);
C.Strings.Free(tname);
return Result /= 0;
end GetMetaTable;
procedure GetMetaTable (L : in Lua_State'Class) is
Success : Boolean := GetMetaTable(L);
begin
if not Success then
raise Program_Error with "No metatable exists for this type";
end if;
end GetMetaTable;
procedure AddOperation (L : in Lua_State'Class; Name : in String; Op : AdaFunction) is
C_name : C.Strings.chars_ptr := C.Strings.New_String(Name);
begin
L.PushAdaClosure(Op, 0);
Internal.lua_setfield(L.L, -2, C_name);
C.Strings.Free(C_name);
end AddOperation;
end Lua.Userdata;
|
-- Lua.Userdata
-- Adding Ada objects to Lua environment
-- Copyright (c) 2015, James Humphry - see LICENSE.md for terms
with System.Address_To_Access_Conversions;
with Interfaces, Interfaces.C, Interfaces.C.Strings;
use Interfaces;
with Lua.Internal, Lua.AuxInternal;
package body Lua.Userdata is
use type Ada.Tags.Tag;
use type C.int;
use type C.size_t;
--
-- *** Conversions between C types and Ada types
--
package Address_To_Ada_Userdata is
new System.Address_To_Access_Conversions(Object => Ada_Userdata);
procedure Push (L : in Lua_State'Class; D : not null access T) is
UserData_Address : System.Address
:= Internal.lua_newuserdata(L.L, (Ada_Userdata'Size+7)/8);
UserData_Access : access Ada_Userdata
:= Address_To_Ada_Userdata.To_Pointer(UserData_Address);
Has_Metatable : Boolean;
begin
UserData_Access.all.Tag := T'Tag;
UserData_Access.all.Data := D;
Has_Metatable := GetMetaTable(L);
if Has_Metatable then
Setmetatable(L, -2);
end if;
end Push;
function ToUserdata (L : in Lua_State'Class; index : in Integer)
return not null access T
is
UserData_Address : System.Address
:= Internal.lua_touserdata(L.L, C.int(index));
UserData_Access : access Ada_Userdata
:= Address_To_Ada_Userdata.To_Pointer(UserData_Address);
begin
if UserData_Access = null then
raise Program_Error with "Attempting to access non-userdata as userdata";
elsif UserData_Access.Tag /= T'Tag then
raise Program_Error with "Attempting invalid userdata type conversion";
end if;
return UserData_Access.Data;
end ToUserdata;
procedure NewMetaTable (L : in Lua_State'Class;
Set_Indexable : Boolean := True) is
tname : C.Strings.chars_ptr
:= C.Strings.New_String("Ada_UserData:" & T'External_Tag);
Result : C.int;
begin
Result := AuxInternal.luaL_newmetatable(L.L, tname);
C.Strings.Free(tname);
if Result = 0 then
raise Program_Error with "Metatable could not be created or already exists";
elsif Set_Indexable then
-- Setting the metatables __index field to itself so any unidentified
-- operations of the form object:operation() will be looked up in the
-- metatable itself
L.PushValue(-1);
L.SetField(-2, "__index");
end if;
end NewMetaTable;
function GetMetaTable (L : in Lua_State'Class) return Boolean is
tname : C.Strings.chars_ptr
:= C.Strings.New_String("Ada_UserData:" & T'External_Tag);
Result : C.int;
begin
Result := Internal.lua_getfield(L.L, C.int(RegistryIndex), tname);
C.Strings.Free(tname);
return Result /= 0;
end GetMetaTable;
procedure GetMetaTable (L : in Lua_State'Class) is
Success : Boolean := GetMetaTable(L);
begin
if not Success then
raise Program_Error with "No metatable exists for this type";
end if;
end GetMetaTable;
procedure AddOperation (L : in Lua_State'Class; Name : in String; Op : AdaFunction) is
C_name : C.Strings.chars_ptr := C.Strings.New_String(Name);
begin
L.PushAdaClosure(Op, 0);
Internal.lua_setfield(L.L, -2, C_name);
C.Strings.Free(C_name);
end AddOperation;
end Lua.Userdata;
|
Correct userdata size calculation
|
Correct userdata size calculation
Per RM-13-3 40 the 'Size attribute is in bits, whereas Lua requires a
byte count for allocating new objects.
|
Ada
|
mit
|
jhumphry/aLua
|
45af98d2017b30ee6cf98a94d24d1a77ecfb6c12
|
src/babel-files-queues.ads
|
src/babel-files-queues.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.Strings.Unbounded;
with Ada.Calendar;
with Ada.Directories;
with Ada.Containers.Vectors;
with Util.Encoders.SHA1;
with Util.Concurrent.Fifos;
with Util.Strings.Vectors;
with ADO;
with Babel.Base.Models;
package Babel.Files.Queues is
-- package Babel.Strategies.Flow/Optimize/Small/Larges/Default/Immediate/Simple/Pipeline/Serial
-- File name
-- Directory info
-- File ID or null
-- File size => sha1, file status, backup
package File_Fifo is new Util.Concurrent.Fifos (Element_Type => File_Type,
Default_Size => 100,
Clear_On_Dequeue => True);
--
-- procedure Execute (Backup : in out Small_Files_Strategy;
-- Queue : in out File_Queue) is
-- begin
-- loop
-- Queue.Dequeue (File, 1.0);
-- -- load file
-- -- compute sha1
-- -- if modified then backup file
-- end loop;
--
-- exception
-- when File_Fifo.Timeout =>
-- null;
-- end Execute;
type File_Queue is tagged limited record
Queue : File_Fifo.Fifo;
end record;
procedure Add_File (Into : in out File_Queue;
File : in File_Type);
type Directory_Queue is limited private;
-- Returns true if there is a directory in the queue.
function Has_Directory (Queue : in Directory_Queue) return Boolean;
-- Get the next directory from the queue.
procedure Peek_Directory (Queue : in out Directory_Queue;
Directory : out Directory_Type);
-- Add the directory in the queue.
procedure Add_Directory (Queue : in out Directory_Queue;
Directory : in Directory_Type);
private
type Directory_Queue is limited record
Directories : Directory_Vector;
end record;
end Babel.Files.Queues;
|
-----------------------------------------------------------------------
-- bkp-files -- File and directories
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Directories;
with Ada.Containers.Vectors;
with Util.Encoders.SHA1;
with Util.Concurrent.Fifos;
with Util.Strings.Vectors;
with ADO;
with Babel.Base.Models;
package Babel.Files.Queues is
-- package Babel.Strategies.Flow/Optimize/Small/Larges/Default/Immediate/Simple/Pipeline/Serial
-- File name
-- Directory info
-- File ID or null
-- File size => sha1, file status, backup
package File_Fifo is new Util.Concurrent.Fifos (Element_Type => File_Type,
Default_Size => 100,
Clear_On_Dequeue => False);
--
-- procedure Execute (Backup : in out Small_Files_Strategy;
-- Queue : in out File_Queue) is
-- begin
-- loop
-- Queue.Dequeue (File, 1.0);
-- -- load file
-- -- compute sha1
-- -- if modified then backup file
-- end loop;
--
-- exception
-- when File_Fifo.Timeout =>
-- null;
-- end Execute;
type File_Queue is tagged limited record
Queue : File_Fifo.Fifo;
end record;
type File_Queue_Access is access all File_Queue'Class;
procedure Add_File (Into : in out File_Queue;
File : in File_Type);
type Directory_Queue is limited private;
-- Returns true if there is a directory in the queue.
function Has_Directory (Queue : in Directory_Queue) return Boolean;
-- Get the next directory from the queue.
procedure Peek_Directory (Queue : in out Directory_Queue;
Directory : out Directory_Type);
-- Add the directory in the queue.
procedure Add_Directory (Queue : in out Directory_Queue;
Directory : in Directory_Type);
private
type Directory_Queue is limited record
Directories : Directory_Vector;
end record;
end Babel.Files.Queues;
|
Declare File_Queue_Access type Do not use the fifo Clear_On_Dequeue because it is not necessary and it is broken
|
Declare File_Queue_Access type
Do not use the fifo Clear_On_Dequeue because it is not necessary and it is broken
|
Ada
|
apache-2.0
|
stcarrez/babel
|
221cd23676732efb960164d42805378fca31bce8
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes;
-- === Documents ===
-- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Node_List_Ref;
TOC : Wiki.Nodes.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes;
-- === Documents ===
-- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Node_List_Ref;
TOC : Wiki.Nodes.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
end record;
end Wiki.Documents;
|
Declare the Is_Empty function to check if a document is empty
|
Declare the Is_Empty function to check if a document is empty
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a07b5c4f82a41cbce8681b7d09f3bfee519cb5a4
|
samples/json.adb
|
samples/json.adb
|
-----------------------------------------------------------------------
-- json -- JSON Reader
-- Copyright (C) 2010, 2011, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
with Util.Serialize.IO.JSON;
with Ada.Containers;
with Mapping;
with Util.Serialize.Mappers.Vector_Mapper;
with Util.Streams.Texts;
with Util.Streams.Buffered;
procedure Json is
use Util.Streams.Buffered;
use Ada.Strings.Unbounded;
use type Mapping.Person_Access;
use type Ada.Containers.Count_Type;
Reader : Util.Serialize.IO.JSON.Parser;
Count : constant Natural := Ada.Command_Line.Argument_Count;
package Person_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Person_Vector,
Element_Mapper => Person_Mapper);
subtype Person_Vector_Context is Person_Vector_Mapper.Vector_Data;
-- Mapping for a list of Person records (stored as a Vector).
Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper;
procedure Print (P : in Mapping.Person_Vector.Cursor);
procedure Print (P : in Mapping.Person);
procedure Print (P : in Mapping.Person) is
begin
Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name));
Ada.Text_IO.Put_Line ("first_name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("last_name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Age : " & Natural'Image (P.Age));
Ada.Text_IO.Put_Line ("Street : " & To_String (P.Addr.Street));
Ada.Text_IO.Put_Line ("City : " & To_String (P.Addr.City));
Ada.Text_IO.Put_Line ("Zip : " & Natural'Image (P.Addr.Zip));
Ada.Text_IO.Put_Line ("Country : " & To_String (P.Addr.Country));
Ada.Text_IO.Put_Line ("Info : " & To_String (P.Addr.Info.Name)
& "=" & To_String (P.Addr.Info.Value));
end Print;
procedure Print (P : in Mapping.Person_Vector.Cursor) is
begin
Print (Mapping.Person_Vector.Element (P));
end Print;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: json file...");
return;
end if;
Person_Vector_Mapping.Set_Mapping (Mapping.Get_Person_Mapper);
Reader.Add_Mapping ("/list", Mapping.Get_Person_Vector_Mapper.all'Access);
Reader.Add_Mapping ("/person", Mapping.Get_Person_Mapper.all'Access);
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
List : aliased Mapping.Person_Vector.Vector;
P : aliased Mapping.Person;
begin
Mapping.Person_Vector_Mapper.Set_Context (Reader, List'Unchecked_Access);
Mapping.Person_Mapper.Set_Context (Reader, P'Unchecked_Access);
Reader.Parse (S);
-- The list now contains our elements.
List.Iterate (Process => Print'Access);
if List.Length = 0 then
Print (P);
end if;
declare
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Mapping.Get_Person_Mapper.Write (Output, P);
Ada.Text_IO.Put_Line ("Person: "
& Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
declare
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Output.Write ("{""list"":");
Mapping.Get_Person_Vector_Mapper.Write (Output, List);
Output.Write ("}");
Ada.Text_IO.Put_Line ("IO:");
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffered_Stream (Output)));
end;
end;
end loop;
end Json;
|
-----------------------------------------------------------------------
-- json -- JSON Reader
-- Copyright (C) 2010, 2011, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
with Util.Serialize.IO.JSON;
with Ada.Containers;
with Mapping;
with Util.Serialize.Mappers.Vector_Mapper;
with Util.Streams.Texts;
with Util.Streams.Buffered;
procedure Json is
use Util.Streams.Buffered;
use Ada.Strings.Unbounded;
use type Mapping.Person_Access;
use type Ada.Containers.Count_Type;
use Mapping;
Reader : Util.Serialize.IO.JSON.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Count : constant Natural := Ada.Command_Line.Argument_Count;
package Person_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Person_Vector,
Element_Mapper => Person_Mapper);
subtype Person_Vector_Context is Person_Vector_Mapper.Vector_Data;
-- Mapping for a list of Person records (stored as a Vector).
Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper;
procedure Print (P : in Mapping.Person_Vector.Cursor);
procedure Print (P : in Mapping.Person);
procedure Print (P : in Mapping.Person) is
begin
Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name));
Ada.Text_IO.Put_Line ("first_name : " & To_String (P.First_Name));
Ada.Text_IO.Put_Line ("last_name : " & To_String (P.Last_Name));
Ada.Text_IO.Put_Line ("Age : " & Natural'Image (P.Age));
Ada.Text_IO.Put_Line ("Street : " & To_String (P.Addr.Street));
Ada.Text_IO.Put_Line ("City : " & To_String (P.Addr.City));
Ada.Text_IO.Put_Line ("Zip : " & Natural'Image (P.Addr.Zip));
Ada.Text_IO.Put_Line ("Country : " & To_String (P.Addr.Country));
Ada.Text_IO.Put_Line ("Info : " & To_String (P.Addr.Info.Name)
& "=" & To_String (P.Addr.Info.Value));
end Print;
procedure Print (P : in Mapping.Person_Vector.Cursor) is
begin
Print (Mapping.Person_Vector.Element (P));
end Print;
begin
if Count = 0 then
Ada.Text_IO.Put_Line ("Usage: json file...");
return;
end if;
Person_Vector_Mapping.Set_Mapping (Mapping.Get_Person_Mapper);
Mapper.Add_Mapping ("/list", Person_Vector_Mapping'Unchecked_Access);
Mapper.Add_Mapping ("/person", Mapping.Get_Person_Mapper.all'Access);
for I in 1 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
List : aliased Mapping.Person_Vector.Vector;
P : aliased Mapping.Person;
begin
Person_Vector_Mapper.Set_Context (Mapper, List'Unchecked_Access);
Mapping.Person_Mapper.Set_Context (Mapper, P'Unchecked_Access);
Reader.Parse (S, Mapper);
-- The list now contains our elements.
List.Iterate (Process => Print'Access);
if List.Length = 0 then
Print (P);
end if;
declare
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Print : aliased Util.Streams.Texts.Print_Stream;
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Size => 10000);
Print.Initialize (Buffer'Unchecked_Access);
Output.Initialize (Print'Unchecked_Access);
Mapping.Get_Person_Mapper.Write (Output, P);
Ada.Text_IO.Put_Line ("Person: "
& Util.Streams.Texts.To_String (Print));
end;
declare
Buffer : aliased Util.Streams.Buffered.Buffered_Stream;
Print : aliased Util.Streams.Texts.Print_Stream;
Output : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Size => 10000);
Print.Initialize (Buffer'Unchecked_Access);
Output.Initialize (Print'Unchecked_Access);
Output.Write ("{""list"":");
Person_Vector_Mapping.Write (Output, List);
Output.Write ("}");
Ada.Text_IO.Put_Line ("IO:");
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Buffered_Stream (Print)));
end;
end;
end loop;
end Json;
|
Update the json samples after changes in parser/mapper interface
|
Update the json samples after changes in parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
580a7e06c65f4364bda8fa383d16266bfa99f7e6
|
src/util-streams-texts.ads
|
src/util-streams-texts.ads
|
-----------------------------------------------------------------------
-- Util.Streams.Files -- File Stream utilities
-- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Streams.Buffered;
with Util.Texts.Transforms;
with Ada.Characters.Handling;
with Ada.Wide_Wide_Characters.Handling;
with Ada.Calendar;
with GNAT.Calendar.Time_IO;
package Util.Streams.Texts is
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Buffered.Buffered_Stream with private;
type Print_Stream_Access is access all Print_Stream'Class;
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer);
-- Write a string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a date on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date);
-- Get the output stream content as a string.
function To_String (Stream : in Buffered.Buffered_Stream'Class) return String;
-- Write a character on the stream.
procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class;
Item : in Character);
-- Write a character on the stream.
procedure Write_Char (Stream : in out Buffered.Buffered_Stream'Class;
Item : in Wide_Wide_Character);
package TR is
new Util.Texts.Transforms (Stream => Buffered.Buffered_Stream'Class,
Char => Character,
Input => String,
Put => Write_Char,
To_Upper => Ada.Characters.Handling.To_Upper,
To_Lower => Ada.Characters.Handling.To_Lower);
package WTR is
new Util.Texts.Transforms (Stream => Buffered.Buffered_Stream'Class,
Char => Wide_Wide_Character,
Input => Wide_Wide_String,
Put => Write_Char,
To_Upper => Ada.Wide_Wide_Characters.Handling.To_Upper,
To_Lower => Ada.Wide_Wide_Characters.Handling.To_Lower);
-- -----------------------
-- Reader stream
-- -----------------------
-- The <b>Reader_Stream</b> is an input stream which provides helper methods
-- for reading text streams.
type Reader_Stream is new Buffered.Buffered_Stream with private;
type Reader_Stream_Access is access all Reader_Stream'Class;
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access);
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False);
private
type Print_Stream is new Buffered.Buffered_Stream with null record;
type Reader_Stream is new Buffered.Buffered_Stream with null record;
end Util.Streams.Texts;
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Streams.Buffered;
with Util.Texts.Transforms;
with Ada.Characters.Handling;
with Ada.Wide_Wide_Characters.Handling;
with Ada.Calendar;
with GNAT.Calendar.Time_IO;
package Util.Streams.Texts is
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Buffered.Buffered_Stream with private;
type Print_Stream_Access is access all Print_Stream'Class;
procedure Initialize (Stream : in out Print_Stream;
To : in Output_Stream_Access);
-- Write a raw character on the stream.
procedure Write (Stream : in out Print_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Print_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer);
-- Write a string on the stream.
-- procedure Write (Stream : in out Print_Stream;
-- Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a date on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date);
-- Get the output stream content as a string.
function To_String (Stream : in Buffered.Buffered_Stream'Class) return String;
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character);
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character);
-- -----------------------
-- Reader stream
-- -----------------------
-- The <b>Reader_Stream</b> is an input stream which provides helper methods
-- for reading text streams.
type Reader_Stream is new Buffered.Buffered_Stream with private;
type Reader_Stream_Access is access all Reader_Stream'Class;
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
procedure Initialize (Stream : in out Reader_Stream;
From : in Input_Stream_Access);
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False);
private
type Print_Stream is new Buffered.Buffered_Stream with null record;
type Reader_Stream is new Buffered.Buffered_Stream with null record;
end Util.Streams.Texts;
|
Refactor Buffered_Stream and Print_Stream - move character related Write operation to the Texts package (Print_Stream) - move the TR and WTR package instantiations in a separate file
|
Refactor Buffered_Stream and Print_Stream
- move character related Write operation to the Texts package (Print_Stream)
- move the TR and WTR package instantiations in a separate file
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
b48deeae90541aac826ca3b46661fe50ad11a9c2
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === 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 policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies (yellow). The framework defines a simple role based security policy and an URL
-- security policy intended to provide security in web applications. The security policy manager
-- reads some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending
-- on the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
--
-- == Principal ==
-- A principal is created by using either the [Security_OpenID OpenID],
-- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces
-- an object that must implement the <tt>Principal</tt> interface. For example:
--
-- P : Security.OpenID.Principal_Access := Security.OpenID.Create_Principal (Auth);
--
-- or
--
-- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token
--
-- The principal is then stored in a security context.
--
-- @include security-contexts.ads
--
-- [Security_Policies Security Policies]
-- [Security_OpenID OpenID]
-- [Security_OAuth OAuth]
--
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === 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 policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies (yellow). The framework defines a simple role based security policy and an URL
-- security policy intended to provide security in web applications. The security policy manager
-- reads some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending
-- on the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
--
-- == Principal ==
-- A principal is created by using either the [Security_Auth OpenID],
-- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces
-- an object that must implement the <tt>Principal</tt> interface. For example:
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth);
--
-- or
--
-- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token
--
-- The principal is then stored in a security context.
--
-- @include security-contexts.ads
--
-- [Security_Policies Security Policies]
-- [Security_Auth OpenID]
-- [Security_OAuth OAuth]
--
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
5019f2e4f08065fb8bf86afadfa5657fb2ab632a
|
regtests/util-properties-tests.adb
|
regtests/util-properties-tests.adb
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use Util.Properties.Basic;
use Util;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : constant Name_Array := Get_Names (Props);
begin
T.Assert (Names'Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : constant Name_Array := Get_Names (Props);
begin
T.Assert (Names'Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
use Util;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
Update the unit test to use the new Get_Names procedure
|
Update the unit test to use the new Get_Names procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c142d7f07e7f03d7a0a4674fd0221b7176fe8d36
|
regtests/util-streams-buffered-tests.adb
|
regtests/util-streams-buffered-tests.adb
|
-----------------------------------------------------------------------
-- streams.buffered.tests -- Unit tests for buffered streams
-- Copyright (C) 2010, 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Texts;
package body Util.Streams.Buffered.Tests is
use Util.Tests;
use Util.Streams.Texts;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Read",
Test_Read_Write'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (String)",
Test_Write'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (Stream_Array)",
Test_Write_Stream'Access);
end Add_Tests;
-- ------------------------------
-- Write on a buffered stream and read what was written.
-- ------------------------------
procedure Test_Read_Write (T : in out Test) is
Stream : Print_Stream;
C : Character;
begin
Stream.Initialize (Size => 4);
Stream.Write ("abcd");
Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Read (C);
Assert_Equals (T, 'a', C, "Invalid character read from the stream");
Stream.Read (C);
Assert_Equals (T, 'b', C, "Invalid character read from the stream");
Stream.Read (C);
Assert_Equals (T, 'c', C, "Invalid character read from the stream");
Stream.Read (C);
Assert_Equals (T, 'd', C, "Invalid character read from the stream");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream");
-- Stream.Write ("abc");
end Test_Read_Write;
-- ------------------------------
-- Write on a buffer and force regular flush on a larger buffer
-- ------------------------------
procedure Test_Write (T : in out Test) is
Big_Stream : aliased Buffered_Stream;
Stream : Buffered_Stream;
Size : Stream_Element_Offset := 0;
Count : constant Stream_Element_Offset := 1000;
Max_Size : constant Stream_Element_Offset := (Count * (Count + 1)) / 2;
begin
Big_Stream.Initialize (Size => Natural (Max_Size));
Stream.Initialize (Output => Big_Stream'Unchecked_Access,
Input => Big_Stream'Unchecked_Access, Size => 13);
for I in 1 .. Count loop
declare
S : Stream_Element_Array (1 .. I);
begin
for J in S'Range loop
S (J) := Stream_Element (J mod 255);
end loop;
Stream.Write (S);
Stream.Flush;
Size := Size + I;
Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed");
-- Verify that 'Big_Stream' holds the expected number of bytes.
Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1,
"Target stream has an invalid write position at "
& Stream_Element_Offset'Image (I));
end;
end loop;
end Test_Write;
-- ------------------------------
-- Write on a buffer and force regular flush on a larger buffer
-- ------------------------------
procedure Test_Write_Stream (T : in out Test) is
Big_Stream : aliased Buffered_Stream;
Stream : Buffered_Stream;
Size : Stream_Element_Offset := 0;
Count : constant Stream_Element_Offset := 200;
Max_Size : constant Stream_Element_Offset := 5728500;
begin
Big_Stream.Initialize (Size => Natural (Max_Size));
for Buf_Size in 1 .. 19 loop
Stream.Initialize (Output => Big_Stream'Unchecked_Access,
Input => Big_Stream'Unchecked_Access, Size => Buf_Size);
for I in 1 .. Count loop
for Repeat in 1 .. 5 loop
declare
S : Stream_Element_Array (1 .. I);
begin
for J in S'Range loop
S (J) := Stream_Element'Val (J mod 255);
end loop;
for J in 1 .. Repeat loop
Stream.Write (S);
end loop;
Stream.Flush;
Size := Size + (I) * Stream_Element_Offset (Repeat);
Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed");
-- Verify that 'Big_Stream' holds the expected number of bytes.
Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1,
"Target stream has an invalid write position at "
& Stream_Element_Offset'Image (I) & " with buffer "
& Natural'Image (Buf_Size) & " repeat " & Natural'Image (Repeat));
end;
end loop;
end loop;
end loop;
Assert_Equals (T, Integer (Max_Size), Integer (Big_Stream.Get_Size), "Invalid final size");
end Test_Write_Stream;
end Util.Streams.Buffered.Tests;
|
-----------------------------------------------------------------------
-- streams.buffered.tests -- Unit tests for buffered streams
-- Copyright (C) 2010, 2011, 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 Util.Streams.Texts;
package body Util.Streams.Buffered.Tests is
use Util.Tests;
use Util.Streams.Texts;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Read",
Test_Read_Write'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (String)",
Test_Write'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (Stream_Array)",
Test_Write_Stream'Access);
end Add_Tests;
-- ------------------------------
-- Write on a buffered stream and read what was written.
-- ------------------------------
procedure Test_Read_Write (T : in out Test) is
Stream : Print_Stream;
Buf : Ada.Strings.Unbounded.Unbounded_String;
begin
Stream.Initialize (Size => 4);
Stream.Write ("abcd");
Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "abcd", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
end Test_Read_Write;
-- ------------------------------
-- Write on a buffer and force regular flush on a larger buffer
-- ------------------------------
procedure Test_Write (T : in out Test) is
Big_Stream : aliased Output_Buffer_Stream;
Stream : Output_Buffer_Stream;
Size : Stream_Element_Offset := 0;
Count : constant Stream_Element_Offset := 1000;
Max_Size : constant Stream_Element_Offset := (Count * (Count + 1)) / 2;
begin
Big_Stream.Initialize (Size => Natural (Max_Size));
Stream.Initialize (Output => Big_Stream'Unchecked_Access, Size => 13);
for I in 1 .. Count loop
declare
S : Stream_Element_Array (1 .. I);
begin
for J in S'Range loop
S (J) := Stream_Element (J mod 255);
end loop;
Stream.Write (S);
Stream.Flush;
Size := Size + I;
Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed");
-- Verify that 'Big_Stream' holds the expected number of bytes.
Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1,
"Target stream has an invalid write position at "
& Stream_Element_Offset'Image (I));
end;
end loop;
end Test_Write;
-- ------------------------------
-- Write on a buffer and force regular flush on a larger buffer
-- ------------------------------
procedure Test_Write_Stream (T : in out Test) is
Big_Stream : aliased Output_Buffer_Stream;
Stream : Output_Buffer_Stream;
Size : Stream_Element_Offset := 0;
Count : constant Stream_Element_Offset := 200;
Max_Size : constant Stream_Element_Offset := 5728500;
begin
Big_Stream.Initialize (Size => Natural (Max_Size));
for Buf_Size in 1 .. 19 loop
Stream.Initialize (Output => Big_Stream'Unchecked_Access,
Size => Buf_Size);
for I in 1 .. Count loop
for Repeat in 1 .. 5 loop
declare
S : Stream_Element_Array (1 .. I);
begin
for J in S'Range loop
S (J) := Stream_Element'Val (J mod 255);
end loop;
for J in 1 .. Repeat loop
Stream.Write (S);
end loop;
Stream.Flush;
Size := Size + (I) * Stream_Element_Offset (Repeat);
Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed");
-- Verify that 'Big_Stream' holds the expected number of bytes.
Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1,
"Target stream has an invalid write position at "
& Stream_Element_Offset'Image (I) & " with buffer "
& Natural'Image (Buf_Size) & " repeat " & Natural'Image (Repeat));
end;
end loop;
end loop;
end loop;
Assert_Equals (T, Integer (Max_Size), Integer (Big_Stream.Get_Size), "Invalid final size");
end Test_Write_Stream;
end Util.Streams.Buffered.Tests;
|
Update the Output_Buffer_Stream test to flush in a string and verify the result
|
Update the Output_Buffer_Stream test to flush in a string and verify the result
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
50ee34da19bd39b22c37cb2d35f181d521bc65f1
|
src/ado-objects.adb
|
src/ado-objects.adb
|
-----------------------------------------------------------------------
-- ADO Objects -- Database objects
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
package body ADO.Objects is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Objects");
-- ------------------------------
-- Compute the hash of the object key.
-- ------------------------------
function Hash (Key : Object_Key) return Ada.Containers.Hash_Type is
Result : Ada.Containers.Hash_Type;
begin
-- @todo SCz 2010-08-03: hash on the object type/class/table
case Key.Of_Type is
when KEY_INTEGER =>
Result := Ada.Containers.Hash_Type (Key.Id);
when KEY_STRING =>
Result := 0;
end case;
return Result;
end Hash;
-- ------------------------------
-- Compare whether the two objects pointed to by Left and Right have the same
-- object key.
-- ------------------------------
function Equivalent_Elements (Left, Right : Object_Key)
return Boolean is
use Ada.Strings.Unbounded;
begin
if Left.Of_Type /= Right.Of_Type then
return False;
end if;
case Left.Of_Type is
when KEY_INTEGER =>
return Left.Id = Right.Id;
when KEY_STRING =>
return Left.Str = Right.Str;
end case;
end Equivalent_Elements;
procedure Adjust (Object : in out Object_Ref) is
begin
if Object.Object /= null then
Util.Concurrent.Counters.Increment (Object.Object.Counter);
end if;
end Adjust;
procedure Finalize (Object : in out Object_Ref) is
Is_Zero : Boolean;
begin
if Object.Object /= null then
Util.Concurrent.Counters.Decrement (Object.Object.Counter, Is_Zero);
if Is_Zero then
Destroy (Object.Object);
Object.Object := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Mark the field identified by <b>Field</b> as modified.
-- ------------------------------
procedure Set_Field (Object : in out Object_Ref'Class;
Field : in Positive) is
begin
if Object.Object = null then
Object.Allocate;
end if;
Object.Object.Modified (Field) := True;
end Set_Field;
-- ------------------------------
-- Check whether this object is initialized or not.
-- ------------------------------
function Is_Null (Object : in Object_Ref'Class) return Boolean is
begin
return Object.Object = null;
end Is_Null;
-- ------------------------------
-- Internal method to get the object record instance.
-- ------------------------------
function Get_Object (Ref : in Object_Ref'Class) return Object_Record_Access is
begin
return Ref.Object;
end Get_Object;
-- ------------------------------
-- Check if the two objects are the same database objects.
-- The comparison is only made on the primary key.
-- Returns true if the two objects have the same primary key.
-- ------------------------------
function "=" (Left : Object_Ref'Class; Right : Object_Ref'Class) return Boolean is
begin
-- Same target object
if Left.Object = Right.Object then
return True;
end if;
-- One of the target object is null
if Left.Object = null or Right.Object = null then
return False;
end if;
return Left.Object.Key = Right.Object.Key;
end "=";
procedure Set_Object (Ref : in out Object_Ref'Class;
Object : in Object_Record_Access) is
Is_Zero : Boolean;
begin
if Ref.Object /= null and Ref.Object /= Object then
Util.Concurrent.Counters.Decrement (Ref.Object.Counter, Is_Zero);
if Is_Zero then
Destroy (Ref.Object);
end if;
end if;
Ref.Object := Object;
end Set_Object;
-- ------------------------------
-- Get the object key
-- ------------------------------
function Get_Id (Ref : in Object_Record'Class) return Object_Key is
begin
return Ref.Key;
end Get_Id;
-- ------------------------------
-- Check if this is a new object.
-- Returns True if an insert is necessary to persist this object.
-- ------------------------------
function Is_Created (Ref : in Object_Record'Class) return Boolean is
begin
return Ref.Is_Created;
end Is_Created;
-- ------------------------------
-- Mark the object as created in the database.
-- ------------------------------
procedure Set_Created (Ref : in out Object_Record'Class) is
begin
Ref.Is_Created := True;
end Set_Created;
-- ------------------------------
-- Check if the field at position <b>Field</b> was modified.
-- ------------------------------
function Is_Modified (Ref : in Object_Record'Class;
Field : in Positive) return Boolean is
begin
return Ref.Modified (Field);
end Is_Modified;
-- ------------------------------
-- Clear the modification flag associated with the field at
-- position <b>Field</b>.
-- ------------------------------
procedure Clear_Modified (Ref : in out Object_Record'Class;
Field : in Positive) is
begin
Ref.Modified (Field) := False;
end Clear_Modified;
end ADO.Objects;
|
-----------------------------------------------------------------------
-- ADO Objects -- Database objects
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
package body ADO.Objects is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Objects");
-- ------------------------------
-- Compute the hash of the object key.
-- ------------------------------
function Hash (Key : Object_Key) return Ada.Containers.Hash_Type is
Result : Ada.Containers.Hash_Type;
begin
-- @todo SCz 2010-08-03: hash on the object type/class/table
case Key.Of_Type is
when KEY_INTEGER =>
Result := Ada.Containers.Hash_Type (Key.Id);
when KEY_STRING =>
Result := 0;
end case;
return Result;
end Hash;
-- ------------------------------
-- Compare whether the two objects pointed to by Left and Right have the same
-- object key.
-- ------------------------------
function Equivalent_Elements (Left, Right : Object_Key)
return Boolean is
use Ada.Strings.Unbounded;
begin
if Left.Of_Type /= Right.Of_Type then
return False;
end if;
case Left.Of_Type is
when KEY_INTEGER =>
return Left.Id = Right.Id;
when KEY_STRING =>
return Left.Str = Right.Str;
end case;
end Equivalent_Elements;
-- ------------------------------
-- Increment the reference counter when an object is copied
-- ------------------------------
procedure Adjust (Object : in out Object_Ref) is
begin
if Object.Object /= null then
Util.Concurrent.Counters.Increment (Object.Object.Counter);
end if;
end Adjust;
procedure Finalize (Object : in out Object_Ref) is
Is_Zero : Boolean;
begin
if Object.Object /= null then
Util.Concurrent.Counters.Decrement (Object.Object.Counter, Is_Zero);
if Is_Zero then
Destroy (Object.Object);
Object.Object := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Mark the field identified by <b>Field</b> as modified.
-- ------------------------------
procedure Set_Field (Object : in out Object_Ref'Class;
Field : in Positive) is
begin
if Object.Object = null then
Object.Allocate;
end if;
Object.Object.Modified (Field) := True;
end Set_Field;
-- ------------------------------
-- Check whether this object is initialized or not.
-- ------------------------------
function Is_Null (Object : in Object_Ref'Class) return Boolean is
begin
return Object.Object = null;
end Is_Null;
-- ------------------------------
-- Internal method to get the object record instance.
-- ------------------------------
function Get_Object (Ref : in Object_Ref'Class) return Object_Record_Access is
begin
return Ref.Object;
end Get_Object;
-- ------------------------------
-- Check if the two objects are the same database objects.
-- The comparison is only made on the primary key.
-- Returns true if the two objects have the same primary key.
-- ------------------------------
function "=" (Left : Object_Ref'Class; Right : Object_Ref'Class) return Boolean is
begin
-- Same target object
if Left.Object = Right.Object then
return True;
end if;
-- One of the target object is null
if Left.Object = null or Right.Object = null then
return False;
end if;
return Left.Object.Key = Right.Object.Key;
end "=";
procedure Set_Object (Ref : in out Object_Ref'Class;
Object : in Object_Record_Access) is
Is_Zero : Boolean;
begin
if Ref.Object /= null and Ref.Object /= Object then
Util.Concurrent.Counters.Decrement (Ref.Object.Counter, Is_Zero);
if Is_Zero then
Destroy (Ref.Object);
end if;
end if;
Ref.Object := Object;
end Set_Object;
-- ------------------------------
-- Get the object key
-- ------------------------------
function Get_Id (Ref : in Object_Record'Class) return Object_Key is
begin
return Ref.Key;
end Get_Id;
-- ------------------------------
-- Check if this is a new object.
-- Returns True if an insert is necessary to persist this object.
-- ------------------------------
function Is_Created (Ref : in Object_Record'Class) return Boolean is
begin
return Ref.Is_Created;
end Is_Created;
-- ------------------------------
-- Mark the object as created in the database.
-- ------------------------------
procedure Set_Created (Ref : in out Object_Record'Class) is
begin
Ref.Is_Created := True;
end Set_Created;
-- ------------------------------
-- Check if the field at position <b>Field</b> was modified.
-- ------------------------------
function Is_Modified (Ref : in Object_Record'Class;
Field : in Positive) return Boolean is
begin
return Ref.Modified (Field);
end Is_Modified;
-- ------------------------------
-- Clear the modification flag associated with the field at
-- position <b>Field</b>.
-- ------------------------------
procedure Clear_Modified (Ref : in out Object_Record'Class;
Field : in Positive) is
begin
Ref.Modified (Field) := False;
end Clear_Modified;
end ADO.Objects;
|
Add comment
|
Add comment
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
a597b318096fc70c878db38891a3a81de3ba723b
|
src/orka/implementation/orka-workers.adb
|
src/orka/implementation/orka-workers.adb
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System.Multiprocessors.Dispatching_Domains;
with Ada.Exceptions;
with Ada.Strings.Fixed;
with Ada.Synchronous_Barriers;
with Ada.Text_IO;
with Orka.OS;
package body Orka.Workers is
Sync_Barrier : Ada.Synchronous_Barriers.Synchronous_Barrier (Count);
protected body Barrier is
procedure Update
(Scene : not null Behaviors.Behavior_Array_Access;
Delta_Time : Duration;
View_Position : Transforms.Vector4) is
begin
Barrier.Scene := Scene;
DT := Delta_Time;
VP := View_Position;
Updated := True;
end Update;
procedure Shutdown is
begin
Stop := True;
end Shutdown;
entry Wait_For_Release
(Scene : out not null Behaviors.Behavior_Array_Access;
Delta_Time : out Duration;
View_Position : out Transforms.Vector4;
Shutdown : out Boolean)
when (Wait_For_Release'Count = Count and Updated) or Ready or Stop is
begin
Scene := Barrier.Scene;
Delta_Time := DT;
View_Position := VP;
Shutdown := Stop;
Ready := Wait_For_Release'Count > 0;
Updated := False;
end Wait_For_Release;
end Barrier;
task body Worker_Task is
package SM renames System.Multiprocessors;
package SF renames Ada.Strings.Fixed;
ID_Image : constant String := Positive'Image (Data.ID);
Scene : not null Behaviors.Behavior_Array_Access := new Behaviors.Behavior_Array (1 .. 0);
DT : Duration;
VP : Transforms.Vector4;
Stop, DC : Boolean := False;
begin
-- Set the CPU affinity of the task to its corresponding CPU core
SM.Dispatching_Domains.Set_CPU (SM.CPU (Data.ID));
Orka.OS.Set_Task_Name ("Worker #" & SF.Trim (ID_Image, Ada.Strings.Left));
loop
Barrier.Wait_For_Release (Scene, DT, VP, Stop);
exit when Stop;
declare
Scene_Count : constant Natural := Scene.all'Length;
Job_Count : constant Natural := Scene_Count / Count;
Rem_Count : constant Natural := Scene_Count rem Count;
Count : constant Natural := Job_Count + (if Data.ID <= Rem_Count then 1 else 0);
Offset : constant Natural := (if Data.ID <= Rem_Count then Data.ID else 1 + Rem_Count);
Start_Index : constant Natural := (Data.ID - 1) * Job_Count + Offset;
End_Index : constant Natural := Start_Index + Count - 1;
begin
for Behavior of Scene.all (Start_Index .. End_Index) loop
Behavior.Update (DT);
end loop;
Ada.Synchronous_Barriers.Wait_For_Release (Sync_Barrier, DC);
for Behavior of Scene.all (Start_Index .. End_Index) loop
Behavior.After_Update (DT, VP);
end loop;
Ada.Synchronous_Barriers.Wait_For_Release (Sync_Barrier, DC);
end;
end loop;
exception
when Error : others =>
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (Error));
end Worker_Task;
function Make_Workers return Worker_Array is
begin
return Result : Worker_Array (1 .. Count) do
for Index in Result'Range loop
Result (Index).ID := Index;
end loop;
end return;
end Make_Workers;
end Orka.Workers;
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System.Multiprocessors.Dispatching_Domains;
with Ada.Exceptions;
with Ada.Strings.Fixed;
with Ada.Synchronous_Barriers;
with Ada.Text_IO;
with Orka.OS;
package body Orka.Workers is
Sync_Barrier : Ada.Synchronous_Barriers.Synchronous_Barrier (Count);
protected body Barrier is
procedure Update
(Scene : not null Behaviors.Behavior_Array_Access;
Delta_Time : Duration;
View_Position : Transforms.Vector4) is
begin
Barrier.Scene := Scene;
DT := Delta_Time;
VP := View_Position;
Updated := True;
end Update;
procedure Shutdown is
begin
Stop := True;
end Shutdown;
entry Wait_For_Release
(Scene : out not null Behaviors.Behavior_Array_Access;
Delta_Time : out Duration;
View_Position : out Transforms.Vector4;
Shutdown : out Boolean)
when (Wait_For_Release'Count = Count and Updated) or Ready or Stop is
begin
Scene := Barrier.Scene;
Delta_Time := DT;
View_Position := VP;
Shutdown := Stop;
Ready := Wait_For_Release'Count > 0;
Updated := False;
end Wait_For_Release;
end Barrier;
procedure Get_Indices
(Scene : Natural;
ID : Positive;
Start_Index, End_Index : out Natural)
is
Job_Count : constant Natural := Scene / Count;
Rem_Count : constant Natural := Scene rem Count;
Count : constant Natural := Job_Count + (if ID <= Rem_Count then 1 else 0);
Offset : constant Natural := (if ID <= Rem_Count then ID else 1 + Rem_Count);
begin
Start_Index := (ID - 1) * Job_Count + Offset;
End_Index := Start_Index + Count - 1;
end Get_Indices;
task body Worker_Task is
package SM renames System.Multiprocessors;
package SF renames Ada.Strings.Fixed;
ID_Image : constant String := Positive'Image (Data.ID);
Scene : not null Behaviors.Behavior_Array_Access := new Behaviors.Behavior_Array (1 .. 0);
DT : Duration;
VP : Transforms.Vector4;
Stop, DC : Boolean := False;
Start_Index, End_Index : Natural;
begin
-- Set the CPU affinity of the task to its corresponding CPU core
SM.Dispatching_Domains.Set_CPU (SM.CPU (Data.ID));
Orka.OS.Set_Task_Name ("Worker #" & SF.Trim (ID_Image, Ada.Strings.Left));
loop
Barrier.Wait_For_Release (Scene, DT, VP, Stop);
exit when Stop;
Get_Indices (Scene.all'Length, Data.ID, Start_Index, End_Index);
for Behavior of Scene.all (Start_Index .. End_Index) loop
Behavior.Update (DT);
end loop;
Ada.Synchronous_Barriers.Wait_For_Release (Sync_Barrier, DC);
for Behavior of Scene.all (Start_Index .. End_Index) loop
Behavior.After_Update (DT, VP);
end loop;
Ada.Synchronous_Barriers.Wait_For_Release (Sync_Barrier, DC);
end loop;
exception
when Error : others =>
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (Error));
end Worker_Task;
function Make_Workers return Worker_Array is
begin
return Result : Worker_Array (1 .. Count) do
for Index in Result'Range loop
Result (Index).ID := Index;
end loop;
end return;
end Make_Workers;
end Orka.Workers;
|
Move computation of indices in worker to a procedure
|
orka: Move computation of indices in worker to a procedure
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
a3dd9b6c434d7a2c0db8b29b947a30b6bf5f52a3
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
--
--
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides security frameworks that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
end Security;
|
Add the permission in the documentation
|
Add the permission in the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
8984bbc4114d179b722ac2b238a5b0b6e051a3fa
|
tools/upnp-ssdp.adb
|
tools/upnp-ssdp.adb
|
-----------------------------------------------------------------------
-- upnp-ssdp -- UPnP SSDP operations
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Calendar;
with System;
with Interfaces.C.Strings;
with Util.Log.Loggers;
package body UPnP.SSDP is
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 ("UPnP.SSDP");
Group : constant String := "239.255.255.250";
type Sockaddr is record
Sa_Family : Interfaces.C.unsigned_short;
Sa_Port : Interfaces.C.unsigned_short;
Sa_Addr : aliased Interfaces.C.char_array (1 .. 8);
end record;
pragma Convention (C, Sockaddr);
type If_Address;
type If_Address_Access is access all If_Address;
type If_Address is record
Ifa_Next : If_Address_Access;
Ifa_Name : Interfaces.C.Strings.chars_ptr;
Ifa_Flags : Interfaces.C.unsigned;
Ifa_Addr : access Sockaddr;
end record;
pragma Convention (C, If_Address);
function Sys_getifaddrs (ifap : access If_Address_Access) return Interfaces.C.int;
pragma Import (C, Sys_getifaddrs, "getifaddrs");
procedure Sys_freeifaddrs (ifap : If_Address_Access);
pragma Import (C, Sys_freeifaddrs, "freeifaddrs");
function Sys_Inet_Ntop (Af : in Interfaces.C.unsigned_short;
Addr : System.Address;
Dst : in Interfaces.C.Strings.chars_ptr;
Size : in Interfaces.C.int) return Interfaces.C.Strings.chars_ptr;
pragma Import (C, Sys_Inet_Ntop, "inet_ntop");
procedure Send (Socket : in GNAT.Sockets.Socket_Type;
Content : in String;
To : access GNAT.Sockets.Sock_Addr_Type);
procedure Receive (Socket : in GNAT.Sockets.Socket_Type;
Target : in String;
Desc : out Ada.Strings.Unbounded.Unbounded_String);
-- ------------------------------
-- Initialize the SSDP scanner by opening the UDP socket.
-- ------------------------------
procedure Initialize (Scanner : in out Scanner_Type) is
Address : aliased GNAT.Sockets.Sock_Addr_Type;
begin
Log.Info ("Discovering gateways on the network");
Address.Addr := GNAT.Sockets.Any_Inet_Addr;
GNAT.Sockets.Create_Socket (Scanner.Socket, GNAT.Sockets.Family_Inet,
GNAT.Sockets.Socket_Datagram);
GNAT.Sockets.Bind_Socket (Scanner.Socket, Address);
GNAT.Sockets.Set_Socket_Option (Scanner.Socket, GNAT.Sockets.IP_Protocol_For_IP_Level,
(GNAT.Sockets.Add_Membership, GNAT.Sockets.Inet_Addr (Group),
GNAT.Sockets.Any_Inet_Addr));
end Initialize;
-- ------------------------------
-- Find the IPv4 addresses of the network interfaces.
-- ------------------------------
procedure Find_IPv4_Addresses (Scanner : in out Scanner_Type;
IPs : out Util.Strings.Sets.Set) is
pragma Unreferenced (Scanner);
use type Interfaces.C.int;
use type Interfaces.C.Strings.chars_ptr;
Iflist : aliased If_Address_Access;
Ifp : If_Address_Access;
R : Interfaces.C.Strings.chars_ptr;
begin
if Sys_getifaddrs (Iflist'Access) = 0 then
R := Interfaces.C.Strings.New_String ("xxx.xxx.xxx.xxx.xxx");
Ifp := Iflist;
while Ifp /= null loop
if Sys_Inet_Ntop (Ifp.Ifa_Addr.Sa_Family, Ifp.Ifa_Addr.Sa_Addr'Address, R, 17)
/= Interfaces.C.Strings.Null_Ptr
then
Log.Debug ("Found interface: {0} - IP {1}",
Interfaces.C.Strings.Value (Ifp.Ifa_Name),
Interfaces.C.Strings.Value (R));
if Interfaces.C.Strings.Value (R) /= "::" then
IPs.Include (Interfaces.C.Strings.Value (R));
end if;
end if;
Ifp := Ifp.Ifa_Next;
end loop;
Interfaces.C.Strings.Free (R);
Sys_freeifaddrs (Iflist);
end if;
end Find_IPv4_Addresses;
procedure Send (Socket : in GNAT.Sockets.Socket_Type;
Content : in String;
To : access GNAT.Sockets.Sock_Addr_Type) is
Last : Ada.Streams.Stream_Element_Offset;
Buf : Ada.Streams.Stream_Element_Array (1 .. Content'Length);
for Buf'Address use Content'Address;
pragma Import (Ada, Buf);
pragma Unreferenced (Last);
begin
GNAT.Sockets.Send_Socket (Socket, Buf, Last, To);
end Send;
-- ------------------------------
-- Send the SSDP discovery UDP packet on the UPnP multicast group 239.255.255.250.
-- Set the "ST" header to the given target. The UDP packet is sent on each interface
-- whose IP address is defined in the set <tt>IPs</tt>.
-- ------------------------------
procedure Send_Discovery (Scanner : in out Scanner_Type;
Target : in String;
IPs : in Util.Strings.Sets.Set) is
Address : aliased GNAT.Sockets.Sock_Addr_Type;
begin
Address.Addr := GNAT.Sockets.Inet_Addr (Group);
Address.Port := 1900;
for IP of IPs loop
GNAT.Sockets.Set_Socket_Option (Scanner.Socket, GNAT.Sockets.IP_Protocol_For_IP_Level,
(GNAT.Sockets.Multicast_If,
GNAT.Sockets.Inet_Addr (IP)));
Log.Debug ("Sending SSDP search for IGD device from {0}", IP);
Send (Scanner.Socket, "M-SEARCH * HTTP/1.1" & ASCII.CR & ASCII.LF &
"HOST: 239.255.255.250:1900" & ASCII.CR & ASCII.LF &
"ST: " & Target & ASCII.CR & ASCII.LF &
"MAN: ""ssdp:discover""" & ASCII.CR & ASCII.LF &
"MX: 2" & ASCII.CR & ASCII.LF, Address'Access);
end loop;
end Send_Discovery;
procedure Receive (Socket : in GNAT.Sockets.Socket_Type;
Target : in String;
Desc : out Ada.Strings.Unbounded.Unbounded_String) is
function Get_Line return String;
Data : Ada.Streams.Stream_Element_Array (0 .. 1500);
Last : Ada.Streams.Stream_Element_Offset;
Pos : Ada.Streams.Stream_Element_Offset := Data'First;
function Get_Line return String is
First : constant Ada.Streams.Stream_Element_Offset := Pos;
begin
while Pos <= Last loop
if Data (Pos) = 16#0D# and then Pos + 1 <= Last and then Data (Pos + 1) = 16#0A# then
declare
Result : String (1 .. Natural (Pos - First));
P : Natural := 1;
begin
for I in First .. Pos - 1 loop
Result (P) := Character'Val (Data (I));
P := P + 1;
end loop;
Log.Debug ("L: {0}", Result);
Pos := Pos + 2;
return Result;
end;
end if;
Pos := Pos + 1;
end loop;
return "";
end Get_Line;
begin
Desc := Ada.Strings.Unbounded.To_Unbounded_String ("");
GNAT.Sockets.Receive_Socket (Socket, Data, Last);
if Get_Line /= "HTTP/1.1 200 OK" then
Log.Debug ("Receive a non HTTP/1.1 response");
return;
end if;
loop
declare
Line : constant String := Get_Line;
Pos : constant Natural := Util.Strings.Index (Line, ':');
Pos2 : Natural := Pos + 1;
begin
exit when Pos = 0;
while Pos2 < Line'Last and then Line (Pos2) = ' ' loop
Pos2 := Pos2 + 1;
end loop;
if Line (1 .. Pos) = "ST:" then
if Line (Pos2 .. Line'Last) /= Target then
return;
end if;
elsif Line (1 .. Pos) = "LOCATION:" then
Desc := Ada.Strings.Unbounded.To_Unbounded_String (Line (Pos2 .. Line'Last));
Log.Debug ("Found a IGD device: {0}", Ada.Strings.Unbounded.To_String (Desc));
return;
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception received", E);
end Receive;
-- ------------------------------
-- Receive the UPnP SSDP discovery messages for the given target.
-- Call the <tt>Process</tt> procedure for each of them. The <tt>Desc</tt> parameter
-- represents the UPnP location header which gives the UPnP XML root descriptor.
-- Wait at most the given time.
-- ------------------------------
procedure Discover (Scanner : in out Scanner_Type;
Target : in String;
Process : not null access procedure (Desc : in String);
Wait : in Duration) is
use type Ada.Calendar.Time;
use type GNAT.Sockets.Selector_Status;
Sel : GNAT.Sockets.Selector_Type;
Rset : GNAT.Sockets.Socket_Set_Type;
Wset : GNAT.Sockets.Socket_Set_Type;
Status : GNAT.Sockets.Selector_Status;
Desc : Ada.Strings.Unbounded.Unbounded_String;
Deadline : constant Ada.Calendar.Time := Ada.Calendar.Clock + Wait;
Remain : Duration;
begin
GNAT.Sockets.Create_Selector (Sel);
loop
GNAT.Sockets.Empty (Rset);
GNAT.Sockets.Empty (Wset);
GNAT.Sockets.Set (Rset, Scanner.Socket);
Remain := Deadline - Ada.Calendar.Clock;
exit when Remain < 0.0;
GNAT.Sockets.Check_Selector (Selector => Sel,
R_Socket_Set => Rset,
W_Socket_Set => Wset,
Status => Status,
Timeout => Remain);
exit when Status = GNAT.Sockets.Expired;
Receive (Scanner.Socket, Target, Desc);
declare
URI : constant String := Ada.Strings.Unbounded.To_String (Desc);
Pos : constant Natural := Util.Strings.Index (URI, ':');
begin
if Pos > 0 and URI (URI'First .. Pos + 2) = "http://" then
Process (URI);
end if;
end;
end loop;
end Discover;
-- ------------------------------
-- Release the socket.
-- ------------------------------
overriding
procedure Finalize (Scanner : in out Scanner_Type) is
use type GNAT.Sockets.Socket_Type;
begin
if Scanner.Socket /= GNAT.Sockets.No_Socket then
GNAT.Sockets.Close_Socket (Scanner.Socket);
end if;
end Finalize;
end UPnP.SSDP;
|
-----------------------------------------------------------------------
-- upnp-ssdp -- UPnP SSDP operations
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Calendar;
with System;
with Interfaces.C.Strings;
with Util.Log.Loggers;
package body UPnP.SSDP is
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 ("UPnP.SSDP");
Group : constant String := "239.255.255.250";
type Sockaddr is record
Sa_Family : Interfaces.C.unsigned_short;
Sa_Port : Interfaces.C.unsigned_short;
Sa_Addr : aliased Interfaces.C.char_array (1 .. 8);
end record;
pragma Convention (C, Sockaddr);
type If_Address;
type If_Address_Access is access all If_Address;
type If_Address is record
Ifa_Next : If_Address_Access;
Ifa_Name : Interfaces.C.Strings.chars_ptr;
Ifa_Flags : Interfaces.C.unsigned;
Ifa_Addr : access Sockaddr;
end record;
pragma Convention (C, If_Address);
function Sys_getifaddrs (ifap : access If_Address_Access) return Interfaces.C.int;
pragma Import (C, Sys_getifaddrs, "getifaddrs");
procedure Sys_freeifaddrs (ifap : If_Address_Access);
pragma Import (C, Sys_freeifaddrs, "freeifaddrs");
function Sys_Inet_Ntop (Af : in Interfaces.C.unsigned_short;
Addr : System.Address;
Dst : in Interfaces.C.Strings.chars_ptr;
Size : in Interfaces.C.int) return Interfaces.C.Strings.chars_ptr;
pragma Import (C, Sys_Inet_Ntop, "inet_ntop");
procedure Send (Socket : in GNAT.Sockets.Socket_Type;
Content : in String;
To : access GNAT.Sockets.Sock_Addr_Type);
procedure Receive (Socket : in GNAT.Sockets.Socket_Type;
Target : in String;
Desc : out Ada.Strings.Unbounded.Unbounded_String);
-- ------------------------------
-- Initialize the SSDP scanner by opening the UDP socket.
-- ------------------------------
procedure Initialize (Scanner : in out Scanner_Type) is
Address : aliased GNAT.Sockets.Sock_Addr_Type;
begin
Log.Info ("Discovering gateways on the network");
Address.Addr := GNAT.Sockets.Any_Inet_Addr;
Address.Port := 0;
GNAT.Sockets.Create_Socket (Scanner.Socket, GNAT.Sockets.Family_Inet,
GNAT.Sockets.Socket_Datagram);
GNAT.Sockets.Bind_Socket (Scanner.Socket, Address);
GNAT.Sockets.Set_Socket_Option (Scanner.Socket, GNAT.Sockets.IP_Protocol_For_IP_Level,
(GNAT.Sockets.Add_Membership, GNAT.Sockets.Inet_Addr (Group),
GNAT.Sockets.Any_Inet_Addr));
end Initialize;
-- ------------------------------
-- Find the IPv4 addresses of the network interfaces.
-- ------------------------------
procedure Find_IPv4_Addresses (Scanner : in out Scanner_Type;
IPs : out Util.Strings.Sets.Set) is
pragma Unreferenced (Scanner);
use type Interfaces.C.int;
use type Interfaces.C.Strings.chars_ptr;
Iflist : aliased If_Address_Access;
Ifp : If_Address_Access;
R : Interfaces.C.Strings.chars_ptr;
begin
if Sys_getifaddrs (Iflist'Access) = 0 then
R := Interfaces.C.Strings.New_String ("xxx.xxx.xxx.xxx.xxx");
Ifp := Iflist;
while Ifp /= null loop
if Sys_Inet_Ntop (Ifp.Ifa_Addr.Sa_Family, Ifp.Ifa_Addr.Sa_Addr'Address, R, 17)
/= Interfaces.C.Strings.Null_Ptr
then
Log.Debug ("Found interface: {0} - IP {1}",
Interfaces.C.Strings.Value (Ifp.Ifa_Name),
Interfaces.C.Strings.Value (R));
if Interfaces.C.Strings.Value (R) /= "::" then
IPs.Include (Interfaces.C.Strings.Value (R));
end if;
end if;
Ifp := Ifp.Ifa_Next;
end loop;
Interfaces.C.Strings.Free (R);
Sys_freeifaddrs (Iflist);
end if;
end Find_IPv4_Addresses;
procedure Send (Socket : in GNAT.Sockets.Socket_Type;
Content : in String;
To : access GNAT.Sockets.Sock_Addr_Type) is
Last : Ada.Streams.Stream_Element_Offset;
Buf : Ada.Streams.Stream_Element_Array (1 .. Content'Length);
for Buf'Address use Content'Address;
pragma Import (Ada, Buf);
pragma Unreferenced (Last);
begin
GNAT.Sockets.Send_Socket (Socket, Buf, Last, To);
end Send;
-- ------------------------------
-- Send the SSDP discovery UDP packet on the UPnP multicast group 239.255.255.250.
-- Set the "ST" header to the given target. The UDP packet is sent on each interface
-- whose IP address is defined in the set <tt>IPs</tt>.
-- ------------------------------
procedure Send_Discovery (Scanner : in out Scanner_Type;
Target : in String;
IPs : in Util.Strings.Sets.Set) is
Address : aliased GNAT.Sockets.Sock_Addr_Type;
begin
Address.Addr := GNAT.Sockets.Inet_Addr (Group);
Address.Port := 1900;
for IP of IPs loop
GNAT.Sockets.Set_Socket_Option (Scanner.Socket, GNAT.Sockets.IP_Protocol_For_IP_Level,
(GNAT.Sockets.Multicast_If,
GNAT.Sockets.Inet_Addr (IP)));
Log.Debug ("Sending SSDP search for IGD device from {0}", IP);
Send (Scanner.Socket, "M-SEARCH * HTTP/1.1" & ASCII.CR & ASCII.LF &
"HOST: 239.255.255.250:1900" & ASCII.CR & ASCII.LF &
"ST: " & Target & ASCII.CR & ASCII.LF &
"MAN: ""ssdp:discover""" & ASCII.CR & ASCII.LF &
"MX: 2" & ASCII.CR & ASCII.LF, Address'Access);
end loop;
end Send_Discovery;
procedure Receive (Socket : in GNAT.Sockets.Socket_Type;
Target : in String;
Desc : out Ada.Strings.Unbounded.Unbounded_String) is
function Get_Line return String;
Data : Ada.Streams.Stream_Element_Array (0 .. 1500);
Last : Ada.Streams.Stream_Element_Offset;
Pos : Ada.Streams.Stream_Element_Offset := Data'First;
function Get_Line return String is
First : constant Ada.Streams.Stream_Element_Offset := Pos;
begin
while Pos <= Last loop
if Data (Pos) = 16#0D# and then Pos + 1 <= Last and then Data (Pos + 1) = 16#0A# then
declare
Result : String (1 .. Natural (Pos - First));
P : Natural := 1;
begin
for I in First .. Pos - 1 loop
Result (P) := Character'Val (Data (I));
P := P + 1;
end loop;
Log.Debug ("L: {0}", Result);
Pos := Pos + 2;
return Result;
end;
end if;
Pos := Pos + 1;
end loop;
return "";
end Get_Line;
begin
Desc := Ada.Strings.Unbounded.To_Unbounded_String ("");
GNAT.Sockets.Receive_Socket (Socket, Data, Last);
if Get_Line /= "HTTP/1.1 200 OK" then
Log.Debug ("Receive a non HTTP/1.1 response");
return;
end if;
loop
declare
Line : constant String := Get_Line;
Pos : constant Natural := Util.Strings.Index (Line, ':');
Pos2 : Natural := Pos + 1;
begin
exit when Pos = 0;
while Pos2 < Line'Last and then Line (Pos2) = ' ' loop
Pos2 := Pos2 + 1;
end loop;
if Line (1 .. Pos) = "ST:" then
if Line (Pos2 .. Line'Last) /= Target then
return;
end if;
elsif Line (1 .. Pos) = "LOCATION:" then
Desc := Ada.Strings.Unbounded.To_Unbounded_String (Line (Pos2 .. Line'Last));
Log.Debug ("Found a IGD device: {0}", Ada.Strings.Unbounded.To_String (Desc));
return;
end if;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception received", E);
end Receive;
-- ------------------------------
-- Receive the UPnP SSDP discovery messages for the given target.
-- Call the <tt>Process</tt> procedure for each of them. The <tt>Desc</tt> parameter
-- represents the UPnP location header which gives the UPnP XML root descriptor.
-- Wait at most the given time.
-- ------------------------------
procedure Discover (Scanner : in out Scanner_Type;
Target : in String;
Process : not null access procedure (Desc : in String);
Wait : in Duration) is
use type Ada.Calendar.Time;
use type GNAT.Sockets.Selector_Status;
Sel : GNAT.Sockets.Selector_Type;
Rset : GNAT.Sockets.Socket_Set_Type;
Wset : GNAT.Sockets.Socket_Set_Type;
Status : GNAT.Sockets.Selector_Status;
Desc : Ada.Strings.Unbounded.Unbounded_String;
Deadline : constant Ada.Calendar.Time := Ada.Calendar.Clock + Wait;
Remain : Duration;
begin
GNAT.Sockets.Create_Selector (Sel);
loop
GNAT.Sockets.Empty (Rset);
GNAT.Sockets.Empty (Wset);
GNAT.Sockets.Set (Rset, Scanner.Socket);
Remain := Deadline - Ada.Calendar.Clock;
exit when Remain < 0.0;
GNAT.Sockets.Check_Selector (Selector => Sel,
R_Socket_Set => Rset,
W_Socket_Set => Wset,
Status => Status,
Timeout => Remain);
exit when Status = GNAT.Sockets.Expired;
Receive (Scanner.Socket, Target, Desc);
declare
URI : constant String := Ada.Strings.Unbounded.To_String (Desc);
Pos : constant Natural := Util.Strings.Index (URI, ':');
begin
if Pos > 0 and URI (URI'First .. Pos + 2) = "http://" then
Process (URI);
end if;
end;
end loop;
end Discover;
-- ------------------------------
-- Release the socket.
-- ------------------------------
overriding
procedure Finalize (Scanner : in out Scanner_Type) is
use type GNAT.Sockets.Socket_Type;
begin
if Scanner.Socket /= GNAT.Sockets.No_Socket then
GNAT.Sockets.Close_Socket (Scanner.Socket);
end if;
end Finalize;
end UPnP.SSDP;
|
Fix the socket port initialization
|
Fix the socket port initialization
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
d368c1fcfb94a367d61136747e26083dca792f19
|
resources/scripts/scrape/yahoo.ads
|
resources/scripts/scrape/yahoo.ads
|
-- Copyright 2017 Jeff Foley. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
local url = require("url")
name = "Yahoo"
type = "scrape"
function start()
setratelimit(1)
end
function vertical(ctx, domain)
for i=1,201,10 do
local ok = scrape(ctx, {['url']=buildurl(domain, i)})
if not ok then
break
end
checkratelimit()
end
end
function buildurl(domain, pagenum)
local next = tostring(pagenum)
local query = "site:" .. domain .. " -domain:www." .. domain
local params = {
p=query,
b=next,
pz="10",
bct="0",
xargs="0",
}
return "https://search.yahoo.com/search?" .. url.build_query_string(params)
end
|
-- Copyright 2017 Jeff Foley. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
local url = require("url")
name = "Yahoo"
type = "scrape"
function start()
setratelimit(1)
end
function vertical(ctx, domain)
for i=1,201,10 do
local ok = scrape(ctx, {['url']=buildurl(domain, i)})
if not ok then
break
end
checkratelimit()
end
end
function buildurl(domain, pagenum)
local query = "site:" .. domain .. " -domain:www." .. domain
local params = {
p=query,
b=pagenum,
pz="10",
bct="0",
xargs="0",
}
return "https://search.yahoo.com/search?" .. url.build_query_string(params)
end
|
Simplify the buildurl function
|
Simplify the buildurl function
|
Ada
|
apache-2.0
|
caffix/amass,caffix/amass
|
881326fa5c74d684d9d8381e7643546bb2543082
|
regtests/babel-base-users-tests.adb
|
regtests/babel-base-users-tests.adb
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Babel.Base.Users.Tests is
use type Util.Strings.Name_Access;
package Caller is new Util.Test_Caller (Test, "Base.Users");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Babel.Base.Users.Find",
Test_Find'Access);
end Add_Tests;
-- ------------------------------
-- Test the Find function resolving some existing user.
-- ------------------------------
procedure Test_Find (T : in out Test) is
Db : Babel.Base.Users.Database;
User : User_Type;
begin
User := Db.Find (0, 0);
T.Assert (User.Name /= null, "User uid=0 was not found");
T.Assert (User.Group /= null, "User gid=0 was not found");
Util.Tests.Assert_Equals (T, "root", User.Name.all, "Invalid root user name");
Util.Tests.Assert_Equals (T, "root", User.Group.all, "Invalid root group name");
User := Db.Find ("bin", "daemon");
T.Assert (User.Name /= null, "User bin was not found");
T.Assert (User.Group /= null, "Group daemon was not found");
Util.Tests.Assert_Equals (T, "bin", User.Name.all, "Invalid 'bin' user name");
Util.Tests.Assert_Equals (T, "daemon", User.Group.all, "Invalid 'daemon' group name");
T.Assert (User.Uid > 0, "Invalid 'bin' uid");
T.Assert (User.Gid > 0, "Invalid 'daemon' gid");
end Test_Find;
end Babel.Base.Users.Tests;
|
-----------------------------------------------------------------------
-- babel-base-users-tests - Unit tests for babel users
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Babel.Base.Users.Tests is
use type Babel.Uid_Type;
use type Babel.Gid_Type;
use type Util.Strings.Name_Access;
package Caller is new Util.Test_Caller (Test, "Base.Users");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Babel.Base.Users.Find",
Test_Find'Access);
Caller.Add_Test (Suite, "Test Babel.Base.Users.Get_Name",
Test_Get_Name'Access);
end Add_Tests;
-- ------------------------------
-- Test the Find function resolving some existing user.
-- ------------------------------
procedure Test_Find (T : in out Test) is
Db : Babel.Base.Users.Database;
User : User_Type;
begin
User := Db.Find (0, 0);
T.Assert (User.Name /= null, "User uid=0 was not found");
T.Assert (User.Group /= null, "User gid=0 was not found");
Util.Tests.Assert_Equals (T, "root", User.Name.all, "Invalid root user name");
Util.Tests.Assert_Equals (T, "root", User.Group.all, "Invalid root group name");
User := Db.Find ("bin", "daemon");
T.Assert (User.Name /= null, "User bin was not found");
T.Assert (User.Group /= null, "Group daemon was not found");
Util.Tests.Assert_Equals (T, "bin", User.Name.all, "Invalid 'bin' user name");
Util.Tests.Assert_Equals (T, "daemon", User.Group.all, "Invalid 'daemon' group name");
T.Assert (User.Uid > 0, "Invalid 'bin' uid");
T.Assert (User.Gid > 0, "Invalid 'daemon' gid");
end Test_Find;
-- ------------------------------
-- Test the Get_Name operation.
-- ------------------------------
procedure Test_Get_Name (T : in out Test) is
Name : Name_Access;
Db : Database;
begin
Name := Db.Get_Name (0);
T.Assert (Name /= null, "Get_Name (0) returned null");
Util.Tests.Assert_Equals (T, "root", Name.all, "Invalid name returned for Get_Name (0)");
Name := Db.Get_Name (1);
T.Assert (Name /= null, "Get_Name (1) returned null");
Name := Db.Get_Name (55555);
T.Assert (Name = null, "Get_Name (55555) returned a non null name");
end Test_Get_Name;
end Babel.Base.Users.Tests;
|
Implement the Test_Get_Name procedure to test the name resolution
|
Implement the Test_Get_Name procedure to test the name resolution
|
Ada
|
apache-2.0
|
stcarrez/babel
|
7c4e3a3b77475bf67e44f203280c38e5f10486c1
|
src/asf-components-widgets-factory.ads
|
src/asf-components-widgets-factory.ads
|
-----------------------------------------------------------------------
-- 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.Factory;
package ASF.Components.Widgets.Factory is
-- Get the widget component factory.
function Definition return ASF.Factory.Factory_Bindings_Access;
end ASF.Components.Widgets.Factory;
|
-----------------------------------------------------------------------
-- widgets-factory -- Factory for widget Components
-- Copyright (C) 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Factory;
package ASF.Components.Widgets.Factory is
-- Register the widget component factory.
procedure Register (Factory : in out ASF.Factory.Component_Factory);
end ASF.Components.Widgets.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
|
f0838df5bb86fcf5a50f2b2b570614d7465d3447
|
src/gen-artifacts-distribs-bundles.adb
|
src/gen-artifacts-distribs-bundles.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-bundles -- Merge bundles for distribution artifact
-- 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.Directories;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Util.Log.Loggers;
with Util.Properties;
package body Gen.Artifacts.Distribs.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Bundles");
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
pragma Unreferenced (Node);
Result : constant Bundle_Rule_Access := new Bundle_Rule;
begin
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Bundle_Rule) return String is
pragma Unreferenced (Rule);
begin
return "bundle";
end Get_Install_Name;
-- ------------------------------
-- Install the file <b>File</b> according to the distribution rule.
-- Merge all the files listed in <b>Files</b> in the target path specified by <b>Path</b>.
-- ------------------------------
overriding
procedure Install (Rule : in Bundle_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
procedure Load_File (File : in File_Record);
procedure Merge_Property (Name, Item : in Util.Properties.Value);
procedure Save_Property (Name, Item : in Util.Properties.Value);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : Ada.Text_IO.File_Type;
Merge : Util.Properties.Manager;
-- ------------------------------
-- Merge the property into the target property list.
-- ------------------------------
procedure Merge_Property (Name, Item : in Util.Properties.Value) is
begin
Merge.Set (Name, Item);
end Merge_Property;
procedure Save_Property (Name, Item : in Util.Properties.Value) is
begin
Ada.Text_IO.Put (Output, Ada.Strings.Unbounded.To_String (Name));
Ada.Text_IO.Put (Output, "=");
Ada.Text_IO.Put_Line (Output, Ada.Strings.Unbounded.To_String (Item));
end Save_Property;
-- ------------------------------
-- Append the file to the output
-- ------------------------------
procedure Load_File (File : in File_Record) is
File_Path : constant String := Rule.Get_Source_Path (File);
Props : Util.Properties.Manager;
begin
Log.Info ("loading {0}", File_Path);
Props.Load_Properties (Path => File_Path);
Props.Iterate (Process => Merge_Property'Access);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Context.Error ("Cannot read {0}: ", File_Path, Ada.Exceptions.Exception_Message (Ex));
end Load_File;
Iter : File_Cursor := Files.First;
begin
Ada.Directories.Create_Path (Dir);
while File_Record_Vectors.Has_Element (Iter) loop
File_Record_Vectors.Query_Element (Iter, Load_File'Access);
File_Record_Vectors.Next (Iter);
end loop;
Ada.Text_IO.Open (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path);
Merge.Iterate (Process => Save_Property'Access);
Ada.Text_IO.Close (File => Output);
end Install;
end Gen.Artifacts.Distribs.Bundles;
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs-bundles -- Merge bundles for distribution artifact
-- 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.Directories;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Util.Log.Loggers;
with Util.Properties;
package body Gen.Artifacts.Distribs.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Bundles");
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
pragma Unreferenced (Node);
Result : constant Bundle_Rule_Access := new Bundle_Rule;
begin
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Bundle_Rule) return String is
pragma Unreferenced (Rule);
begin
return "bundle";
end Get_Install_Name;
-- ------------------------------
-- Install the file <b>File</b> according to the distribution rule.
-- Merge all the files listed in <b>Files</b> in the target path specified by <b>Path</b>.
-- ------------------------------
overriding
procedure Install (Rule : in Bundle_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
procedure Load_File (File : in File_Record);
procedure Merge_Property (Name, Item : in Util.Properties.Value);
procedure Save_Property (Name, Item : in Util.Properties.Value);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : Ada.Text_IO.File_Type;
Merge : Util.Properties.Manager;
-- ------------------------------
-- Merge the property into the target property list.
-- ------------------------------
procedure Merge_Property (Name, Item : in Util.Properties.Value) is
begin
Merge.Set (Name, Item);
end Merge_Property;
procedure Save_Property (Name, Item : in Util.Properties.Value) is
begin
Ada.Text_IO.Put (Output, Ada.Strings.Unbounded.To_String (Name));
Ada.Text_IO.Put (Output, "=");
Ada.Text_IO.Put_Line (Output, Ada.Strings.Unbounded.To_String (Item));
end Save_Property;
-- ------------------------------
-- Append the file to the output
-- ------------------------------
procedure Load_File (File : in File_Record) is
File_Path : constant String := Rule.Get_Source_Path (File);
Props : Util.Properties.Manager;
begin
Log.Info ("loading {0}", File_Path);
Props.Load_Properties (Path => File_Path);
Props.Iterate (Process => Merge_Property'Access);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Context.Error ("Cannot read {0}: ", File_Path, Ada.Exceptions.Exception_Message (Ex));
end Load_File;
Iter : File_Cursor := Files.First;
begin
Ada.Directories.Create_Path (Dir);
while File_Record_Vectors.Has_Element (Iter) loop
File_Record_Vectors.Query_Element (Iter, Load_File'Access);
File_Record_Vectors.Next (Iter);
end loop;
Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path);
Merge.Iterate (Process => Save_Property'Access);
Ada.Text_IO.Close (File => Output);
end Install;
end Gen.Artifacts.Distribs.Bundles;
|
Fix creation of target bundle file
|
Fix creation of target bundle file
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3a09eddbdb45bc00c7e00d4f31bebf1b37df6845
|
src/security-controllers-roles.adb
|
src/security-controllers-roles.adb
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers.Record_Mapper;
package body Security.Controllers.Roles is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
-- ------------------------------
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class)
return Boolean is
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
for I in Handler.Roles'Range loop
-- if P.Has_Role (Handler.Roles (I)) then
return True;
-- end if;
end loop;
end if;
return False;
end Has_Permission;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Permissions.Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>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.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Manager;
Config_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Controllers.Roles;
|
-----------------------------------------------------------------------
-- security-controllers-roles -- Simple role base security
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.Mappers.Record_Mapper;
package body Security.Controllers.Roles is
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- one of the role defined in the <b>Handler</b>.
-- ------------------------------
function Has_Permission (Handler : in Role_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
for I in Handler.Roles'Range loop
-- if P.Has_Role (Handler.Roles (I)) then
return True;
-- end if;
end loop;
end if;
return False;
end Has_Permission;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Permissions.Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>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.
-- ------------------------------
package body Reader_Config is
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Manager;
Config_Mapper.Set_Context (Reader, Config'Unchecked_Access);
end Reader_Config;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Controllers.Roles;
|
Add permission parameter
|
Add permission parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
195833802d8f3daa3f4c2b252e7b6a59f295481e
|
src/el-beans.ads
|
src/el-beans.ads
|
-----------------------------------------------------------------------
-- EL.Beans -- Interface Definition with Getter and Setters
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Objects;
package EL.Beans is
-- Exception raised when the value identified by a name is not
-- recognized.
No_Value : exception;
-- ------------------------------
-- Read-only Bean interface.
-- ------------------------------
-- The ''Readonly_Bean'' interface allows to plug a complex
-- runtime object to the expression resolver. This interface
-- must be implemented by any tagged record that should be
-- accessed as a variable for an expression.
--
-- For example, if 'foo' is bound to an object implementing that
-- interface, expressions like 'foo.name' will resolve to 'foo'
-- and the 'Get_Value' method will be called with 'name'.
--
type Readonly_Bean is interface;
type Readonly_Bean_Access is access all Readonly_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : Readonly_Bean;
Name : String) return EL.Objects.Object is abstract;
-- ------------------------------
-- Bean interface.
-- ------------------------------
-- The ''Bean'' interface allows to modify a property value.
type Bean is interface and Readonly_Bean;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
procedure Set_Value (From : in out Bean;
Name : in String;
Value : in EL.Objects.Object) is abstract;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> interface gives access to a list of objects.
type List_Bean is interface and Readonly_Bean;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
function Get_Count (From : List_Bean) return Natural is abstract;
-- Set the current row index. Valid row indexes start at 1.
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural) is abstract;
-- Get the element at the current row index.
function Get_Row (From : List_Bean) return EL.Objects.Object is abstract;
end EL.Beans;
|
-----------------------------------------------------------------------
-- EL.Beans -- Interface Definition with Getter and Setters
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Objects;
package EL.Beans is
-- Exception raised when the value identified by a name is not
-- recognized.
No_Value : exception;
-- ------------------------------
-- Read-only Bean interface.
-- ------------------------------
-- The ''Readonly_Bean'' interface allows to plug a complex
-- runtime object to the expression resolver. This interface
-- must be implemented by any tagged record that should be
-- accessed as a variable for an expression.
--
-- For example, if 'foo' is bound to an object implementing that
-- interface, expressions like 'foo.name' will resolve to 'foo'
-- and the 'Get_Value' method will be called with 'name'.
--
type Readonly_Bean is limited interface;
type Readonly_Bean_Access is access all Readonly_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : Readonly_Bean;
Name : String) return EL.Objects.Object is abstract;
-- ------------------------------
-- Bean interface.
-- ------------------------------
-- The ''Bean'' interface allows to modify a property value.
type Bean is limited interface and Readonly_Bean;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
procedure Set_Value (From : in out Bean;
Name : in String;
Value : in EL.Objects.Object) is abstract;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> interface gives access to a list of objects.
type List_Bean is limited interface and Readonly_Bean;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
function Get_Count (From : List_Bean) return Natural is abstract;
-- Set the current row index. Valid row indexes start at 1.
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural) is abstract;
-- Get the element at the current row index.
function Get_Row (From : List_Bean) return EL.Objects.Object is abstract;
end EL.Beans;
|
Make the interface limited to allow limited types to implement the bean interfaces.
|
Make the interface limited to allow limited types to implement the bean interfaces.
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
84e8591579b50e1816e7008ca8f024fb943acddf
|
src/asf-servlets-faces-mappers.adb
|
src/asf-servlets-faces-mappers.adb
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- Copyright (C) 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Servlet.Routes.Servlets;
with Servlet.Core;
with ASF.Routes;
package body ASF.Servlets.Faces.Mappers is
use type ASF.Routes.Route_Type_Access;
use type Servlet.Core.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Servlet.Core.Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Serv : constant Servlet_Access := Servlet.Core.Get_Servlet (Disp);
begin
if Serv = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
return Serv; -- Servlet.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
To : ASF.Routes.Faces_Route_Type_Access;
begin
if Route.Is_Null then
To := new ASF.Routes.Faces_Route_Type;
To.View := Ada.Strings.Unbounded.To_Unbounded_String (View);
To.Servlet := Servlet;
Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access);
end if;
end Insert;
begin
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
ELContext => N.Context.all,
Process => Insert'Access);
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
-----------------------------------------------------------------------
-- asf-servlets-faces-mappers -- Read faces specific configuration files
-- Copyright (C) 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Servlet.Core;
with ASF.Routes;
package body ASF.Servlets.Faces.Mappers is
use type ASF.Routes.Route_Type_Access;
use type Servlet.Core.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access;
function Find_Servlet (Container : in Servlet_Registry_Access;
View : in String)
return ASF.Servlets.Servlet_Access is
Disp : constant Servlet.Core.Request_Dispatcher := Container.Get_Request_Dispatcher (View);
Serv : constant Servlet_Access := Servlet.Core.Get_Servlet (Disp);
begin
if Serv = null then
raise Util.Serialize.Mappers.Field_Error with "No servlet mapped to view " & View;
end if;
return Serv; -- Servlet.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet;
end Find_Servlet;
-- ------------------------------
-- Save in the servlet config object the value associated with the given field.
-- When the URL_MAPPING, URL_PATTERN, VIEW_ID field
-- is reached, insert the new configuration rule in the servlet registry.
-- ------------------------------
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Field is
when URL_PATTERN =>
N.URL_Pattern := Value;
when VIEW_ID =>
N.View_Id := Value;
when URL_MAPPING =>
declare
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
View : constant String := To_String (N.View_Id);
Servlet : constant ASF.Servlets.Servlet_Access := Find_Servlet (N.Handler, View);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
To : ASF.Routes.Faces_Route_Type_Access;
begin
if Route.Is_Null then
To := new ASF.Routes.Faces_Route_Type;
To.View := Ada.Strings.Unbounded.To_Unbounded_String (View);
To.Servlet := Servlet;
Route := ASF.Routes.Route_Type_Refs.Create (To.all'Access);
end if;
end Insert;
begin
N.Handler.Add_Route (Pattern => To_String (N.URL_Pattern),
ELContext => N.Context.all,
Process => Insert'Access);
end;
end case;
end Set_Member;
SMapper : aliased Servlet_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the servlet and mapping rules <b>url-mapping</b>.
-- ------------------------------
package body Reader_Config is
begin
Mapper.Add_Mapping ("faces-config", SMapper'Access);
Mapper.Add_Mapping ("module", SMapper'Access);
Mapper.Add_Mapping ("web-app", SMapper'Access);
Config.Handler := Handler;
Config.Context := Context;
Servlet_Mapper.Set_Context (Mapper, Config'Unchecked_Access);
end Reader_Config;
begin
SMapper.Add_Mapping ("url-mapping", URL_MAPPING);
SMapper.Add_Mapping ("url-mapping/pattern", URL_PATTERN);
SMapper.Add_Mapping ("url-mapping/view-id", VIEW_ID);
end ASF.Servlets.Faces.Mappers;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
de99edcb33ddab46baaa7ad70108625411378443
|
awa/samples/src/atlas-server.adb
|
awa/samples/src/atlas-server.adb
|
-----------------------------------------------------------------------
-- Atlas-server -- Application server
-- Copyright (C) 2011 unknown
-- Written by unknown ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Log.loggers;
with ASF.Server.Web;
with Atlas.Applications;
procedure Atlas.Server is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server");
App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application;
WS : ASF.Server.Web.AWS_Container;
begin
Atlas.Applications.Initialize (App);
WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access);
Log.Info ("Connect you browser to: http://localhost:8080/atlas/index.html");
WS.Start;
delay 365.0 * 24.0 * 3600.0;
App.Close;
exception
when E: others =>
Log.Error ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Atlas.Server;
|
-----------------------------------------------------------------------
-- Atlas-server -- Application server
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Log.Loggers;
with ASF.Server.Web;
with Atlas.Applications;
procedure Atlas.Server is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server");
App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application;
WS : ASF.Server.Web.AWS_Container;
begin
Atlas.Applications.Initialize (App);
WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access);
Log.Info ("Connect you browser to: http://localhost:8080/atlas/index.html");
WS.Start;
delay 365.0 * 24.0 * 3600.0;
App.Close;
exception
when E : others =>
Log.Error ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Atlas.Server;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
75f608ea7c691cbc55ed1fef7a9f73300290bb75
|
src/port_specification-makefile.adb
|
src/port_specification-makefile.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Text_IO;
with Ada.Characters.Latin_1;
package body Port_Specification.Makefile is
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
--------------------------------------------------------------------------------------------
-- generator
--------------------------------------------------------------------------------------------
procedure generator
(specs : Portspecs;
variant : String;
opsys : supported_opsys;
arch_standard : supported_arch;
osrelease : String;
osmajor : String;
osversion : String;
option_string : String;
output_file : String
)
is
procedure send (data : String; use_put : Boolean := False);
procedure send (varname, value : String);
procedure send (varname : String; value : HT.Text);
procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1);
procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1);
procedure send (varname : String; value : Boolean; dummy : Boolean);
procedure send (varname : String; value, default : Integer);
procedure print_item (position : string_crate.Cursor);
procedure dump_list (position : list_crate.Cursor);
procedure dump_distfiles (position : string_crate.Cursor);
procedure dump_ext_zip (position : string_crate.Cursor);
procedure dump_ext_7z (position : string_crate.Cursor);
procedure dump_ext_lha (position : string_crate.Cursor);
procedure dump_extract_head_tail (position : list_crate.Cursor);
procedure dump_dirty_extract (position : string_crate.Cursor);
write_to_file : constant Boolean := (output_file /= "");
makefile_handle : TIO.File_Type;
varname_prefix : HT.Text;
procedure send (data : String; use_put : Boolean := False) is
begin
if write_to_file then
if use_put then
TIO.Put (makefile_handle, data);
else
TIO.Put_Line (makefile_handle, data);
end if;
else
if use_put then
TIO.Put (data);
else
TIO.Put_Line (data);
end if;
end if;
end send;
procedure send (varname, value : String) is
begin
send (varname & LAT.Equals_Sign & value);
end send;
procedure send (varname : String; value : HT.Text) is
begin
if not HT.IsBlank (value) then
send (varname & LAT.Equals_Sign & HT.USS (value));
end if;
end send;
procedure send (varname : String; value : Boolean; dummy : Boolean) is
begin
if value then
send (varname & LAT.Equals_Sign & "yes");
end if;
end send;
procedure send (varname : String; value, default : Integer) is
begin
if value /= default then
send (varname & LAT.Equals_Sign & HT.int2str (value));
end if;
end send;
procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1) is
begin
if crate.Is_Empty then
return;
end if;
case flavor is
when 1 =>
send (varname & "=", True);
crate.Iterate (Process => print_item'Access);
send ("");
when 2 =>
varname_prefix := HT.SUS (varname);
crate.Iterate (Process => dump_distfiles'Access);
when 3 =>
crate.Iterate (Process => dump_ext_zip'Access);
when 4 =>
crate.Iterate (Process => dump_ext_7z'Access);
when 5 =>
crate.Iterate (Process => dump_ext_lha'Access);
when 7 =>
crate.Iterate (Process => dump_dirty_extract'Access);
when others =>
null;
end case;
end send;
procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1) is
begin
varname_prefix := HT.SUS (varname);
case flavor is
when 1 => crate.Iterate (Process => dump_list'Access);
when 6 => crate.Iterate (Process => dump_extract_head_tail'Access);
when others => null;
end case;
end send;
procedure dump_list (position : list_crate.Cursor)
is
NDX : String := HT.USS (varname_prefix) & "_" &
HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign;
begin
send (NDX, True);
list_crate.Element (position).list.Iterate (Process => print_item'Access);
send ("");
end dump_list;
procedure dump_extract_head_tail (position : list_crate.Cursor)
is
NDX : String := HT.USS (varname_prefix) & "_" &
HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign;
begin
if not list_crate.Element (position).list.Is_Empty then
send (NDX, True);
list_crate.Element (position).list.Iterate (Process => print_item'Access);
send ("");
end if;
end dump_extract_head_tail;
procedure print_item (position : string_crate.Cursor)
is
index : Natural := string_crate.To_Index (position);
begin
if index > 1 then
send (" ", True);
end if;
send (HT.USS (string_crate.Element (position)), True);
end print_item;
procedure dump_distfiles (position : string_crate.Cursor)
is
index : Natural := string_crate.To_Index (position);
NDX : String := HT.USS (varname_prefix) & "_" & HT.int2str (index) & LAT.Equals_Sign;
begin
send (NDX & HT.USS (string_crate.Element (position)));
end dump_distfiles;
procedure dump_ext_zip (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=/usr/bin/unzip -qo");
send ("EXTRACT_TAIL_" & N & "=-d ${EXTRACT_WRKDIR_" & N & "}");
end dump_ext_zip;
procedure dump_ext_7z (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=7z x -bd -y -o${EXTRACT_WRKDIR_" & N & "} >/dev/null");
send ("EXTRACT_TAIL_" & N & "=# empty");
end dump_ext_7z;
procedure dump_ext_lha (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=lha xfpw=${EXTRACT_WRKDIR_" & N & "}");
send ("EXTRACT_TAIL_" & N & "=# empty");
end dump_ext_lha;
procedure dump_dirty_extract (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("DIRTY_EXTRACT_" & N & "=yes");
end dump_dirty_extract;
begin
if not specs.variant_exists (variant) then
TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!");
return;
end if;
if write_to_file then
TIO.Create (File => makefile_handle,
Mode => TIO.Out_File,
Name => output_file);
end if;
-- TODO: Check these to see if they are actually used.
-- The pkg manifests did use many of these, but they will be generated by ravenadm
send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF);
send ("NAMEBASE", HT.USS (specs.namebase));
send ("VERSION", HT.USS (specs.version));
send ("REVISION", specs.revision, 0);
send ("EPOCH", specs.epoch, 0);
send ("KEYWORDS", specs.keywords); -- probably remove
send ("VARIANT", variant);
send ("DL_SITES", specs.dl_sites);
send ("DISTFILE", specs.distfiles, 2);
send ("DIST_SUBDIR", specs.dist_subdir);
send ("DISTNAME", specs.distname);
send ("DF_INDEX", specs.df_index);
send ("EXTRACT_ONLY", specs.extract_only);
send ("DIRTY_EXTRACT", specs.extract_dirty, 7);
send ("ZIP-EXTRACT", specs.extract_zip, 3);
send ("7Z-EXTRACT", specs.extract_7z, 4);
send ("LHA-EXTRACT", specs.extract_lha, 5);
send ("EXTRACT_HEAD", specs.extract_head, 6);
send ("EXTRACT_TAIL", specs.extract_tail, 6);
send ("NO_BUILD", specs.skip_build, True);
send ("BUILD_WRKSRC", specs.build_wrksrc);
send ("BUILD_TARGET", specs.build_target);
send ("MAKEFILE", specs.makefile);
send ("MAKE_ENV", specs.make_env);
send ("MAKE_ARGS", specs.make_args);
send ("CFLAGS", specs.cflags);
send ("CXXFLAGS", specs.cxxflags);
send ("CPPFLAGS", specs.cppflags);
send ("LDFLAGS", specs.ldflags);
send ("SINGLE_JOB", specs.single_job, True);
send ("DESTDIR_VIA_ENV", specs.destdir_env, True);
send ("DESTDIRNAME", specs.destdirname);
-- TODO: This is not correct, placeholder. rethink.
send (".include " & LAT.Quotation & "/usr/raven/share/mk/raven.mk" & LAT.Quotation);
if write_to_file then
TIO.Close (makefile_handle);
end if;
exception
when others =>
if TIO.Is_Open (makefile_handle) then
TIO.Close (makefile_handle);
end if;
end generator;
end Port_Specification.Makefile;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Utilities;
with Ada.Text_IO;
with Ada.Characters.Latin_1;
package body Port_Specification.Makefile is
package UTL renames Utilities;
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
--------------------------------------------------------------------------------------------
-- generator
--------------------------------------------------------------------------------------------
procedure generator
(specs : Portspecs;
variant : String;
opsys : supported_opsys;
arch_standard : supported_arch;
osrelease : String;
osmajor : String;
osversion : String;
option_string : String;
output_file : String
)
is
procedure send (data : String; use_put : Boolean := False);
procedure send (varname, value : String);
procedure send (varname : String; value : HT.Text);
procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1);
procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1);
procedure send (varname : String; value : Boolean; dummy : Boolean);
procedure send (varname : String; value, default : Integer);
procedure print_item (position : string_crate.Cursor);
procedure dump_list (position : list_crate.Cursor);
procedure dump_distfiles (position : string_crate.Cursor);
procedure dump_ext_zip (position : string_crate.Cursor);
procedure dump_ext_7z (position : string_crate.Cursor);
procedure dump_ext_lha (position : string_crate.Cursor);
procedure dump_line (position : string_crate.Cursor);
procedure dump_extract_head_tail (position : list_crate.Cursor);
procedure dump_dirty_extract (position : string_crate.Cursor);
procedure dump_standard_target (target : String);
procedure dump_opsys_target (target : String);
write_to_file : constant Boolean := (output_file /= "");
makefile_handle : TIO.File_Type;
varname_prefix : HT.Text;
procedure send (data : String; use_put : Boolean := False) is
begin
if write_to_file then
if use_put then
TIO.Put (makefile_handle, data);
else
TIO.Put_Line (makefile_handle, data);
end if;
else
if use_put then
TIO.Put (data);
else
TIO.Put_Line (data);
end if;
end if;
end send;
procedure send (varname, value : String) is
begin
send (varname & LAT.Equals_Sign & value);
end send;
procedure send (varname : String; value : HT.Text) is
begin
if not HT.IsBlank (value) then
send (varname & LAT.Equals_Sign & HT.USS (value));
end if;
end send;
procedure send (varname : String; value : Boolean; dummy : Boolean) is
begin
if value then
send (varname & LAT.Equals_Sign & "yes");
end if;
end send;
procedure send (varname : String; value, default : Integer) is
begin
if value /= default then
send (varname & LAT.Equals_Sign & HT.int2str (value));
end if;
end send;
procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1) is
begin
if crate.Is_Empty then
return;
end if;
case flavor is
when 1 =>
send (varname & "=", True);
crate.Iterate (Process => print_item'Access);
send ("");
when 2 =>
varname_prefix := HT.SUS (varname);
crate.Iterate (Process => dump_distfiles'Access);
when 3 =>
crate.Iterate (Process => dump_ext_zip'Access);
when 4 =>
crate.Iterate (Process => dump_ext_7z'Access);
when 5 =>
crate.Iterate (Process => dump_ext_lha'Access);
when 7 =>
crate.Iterate (Process => dump_dirty_extract'Access);
when others =>
null;
end case;
end send;
procedure send (varname : String; crate : list_crate.Map; flavor : Positive := 1) is
begin
varname_prefix := HT.SUS (varname);
case flavor is
when 1 => crate.Iterate (Process => dump_list'Access);
when 6 => crate.Iterate (Process => dump_extract_head_tail'Access);
when others => null;
end case;
end send;
procedure dump_list (position : list_crate.Cursor)
is
NDX : String := HT.USS (varname_prefix) & "_" &
HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign;
begin
send (NDX, True);
list_crate.Element (position).list.Iterate (Process => print_item'Access);
send ("");
end dump_list;
procedure dump_extract_head_tail (position : list_crate.Cursor)
is
NDX : String := HT.USS (varname_prefix) & "_" &
HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign;
begin
if not list_crate.Element (position).list.Is_Empty then
send (NDX, True);
list_crate.Element (position).list.Iterate (Process => print_item'Access);
send ("");
end if;
end dump_extract_head_tail;
procedure print_item (position : string_crate.Cursor)
is
index : Natural := string_crate.To_Index (position);
begin
if index > 1 then
send (" ", True);
end if;
send (HT.USS (string_crate.Element (position)), True);
end print_item;
procedure dump_line (position : string_crate.Cursor) is
begin
send (HT.USS (string_crate.Element (position)));
end dump_line;
procedure dump_distfiles (position : string_crate.Cursor)
is
index : Natural := string_crate.To_Index (position);
NDX : String := HT.USS (varname_prefix) & "_" & HT.int2str (index) & LAT.Equals_Sign;
begin
send (NDX & HT.USS (string_crate.Element (position)));
end dump_distfiles;
procedure dump_ext_zip (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=/usr/bin/unzip -qo");
send ("EXTRACT_TAIL_" & N & "=-d ${EXTRACT_WRKDIR_" & N & "}");
end dump_ext_zip;
procedure dump_ext_7z (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=7z x -bd -y -o${EXTRACT_WRKDIR_" & N & "} >/dev/null");
send ("EXTRACT_TAIL_" & N & "=# empty");
end dump_ext_7z;
procedure dump_ext_lha (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("EXTRACT_HEAD_" & N & "=lha xfpw=${EXTRACT_WRKDIR_" & N & "}");
send ("EXTRACT_TAIL_" & N & "=# empty");
end dump_ext_lha;
procedure dump_dirty_extract (position : string_crate.Cursor)
is
N : String := HT.USS (string_crate.Element (position));
begin
send ("DIRTY_EXTRACT_" & N & "=yes");
end dump_dirty_extract;
procedure dump_standard_target (target : String)
is
target_text : HT.Text := HT.SUS (target);
begin
if specs.make_targets.Contains (target_text) then
send (target & LAT.Colon);
specs.make_targets.Element (target_text).list.Iterate (Process => dump_line'Access);
send ("");
end if;
end dump_standard_target;
procedure dump_opsys_target (target : String)
is
os_target : HT.Text := HT.SUS (target & LAT.Hyphen & UTL.lower_opsys (opsys));
std_target : String := target & "-opsys";
begin
if specs.make_targets.Contains (os_target) then
send (std_target & LAT.Colon);
specs.make_targets.Element (os_target).list.Iterate (Process => dump_line'Access);
send ("");
end if;
end dump_opsys_target;
begin
if not specs.variant_exists (variant) then
TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!");
return;
end if;
if write_to_file then
TIO.Create (File => makefile_handle,
Mode => TIO.Out_File,
Name => output_file);
end if;
-- TODO: Check these to see if they are actually used.
-- The pkg manifests did use many of these, but they will be generated by ravenadm
send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF);
send ("NAMEBASE", HT.USS (specs.namebase));
send ("VERSION", HT.USS (specs.version));
send ("REVISION", specs.revision, 0);
send ("EPOCH", specs.epoch, 0);
send ("KEYWORDS", specs.keywords); -- probably remove
send ("VARIANT", variant);
send ("DL_SITES", specs.dl_sites);
send ("DISTFILE", specs.distfiles, 2);
send ("DIST_SUBDIR", specs.dist_subdir);
send ("DISTNAME", specs.distname);
send ("DF_INDEX", specs.df_index);
send ("EXTRACT_ONLY", specs.extract_only);
send ("DIRTY_EXTRACT", specs.extract_dirty, 7);
send ("ZIP-EXTRACT", specs.extract_zip, 3);
send ("7Z-EXTRACT", specs.extract_7z, 4);
send ("LHA-EXTRACT", specs.extract_lha, 5);
send ("EXTRACT_HEAD", specs.extract_head, 6);
send ("EXTRACT_TAIL", specs.extract_tail, 6);
send ("NO_BUILD", specs.skip_build, True);
send ("BUILD_WRKSRC", specs.build_wrksrc);
send ("BUILD_TARGET", specs.build_target);
send ("MAKEFILE", specs.makefile);
send ("MAKE_ENV", specs.make_env);
send ("MAKE_ARGS", specs.make_args);
send ("CFLAGS", specs.cflags);
send ("CXXFLAGS", specs.cxxflags);
send ("CPPFLAGS", specs.cppflags);
send ("LDFLAGS", specs.ldflags);
send ("SINGLE_JOB", specs.single_job, True);
send ("DESTDIR_VIA_ENV", specs.destdir_env, True);
send ("DESTDIRNAME", specs.destdirname);
declare
function get_phasestr (index : Positive) return String;
function get_prefix (index : Positive) return String;
function get_phasestr (index : Positive) return String is
begin
case index is
when 1 => return "fetch";
when 2 => return "extract";
when 3 => return "patch";
when 4 => return "configure";
when 5 => return "build";
when 6 => return "install";
when others => return "";
end case;
end get_phasestr;
function get_prefix (index : Positive) return String is
begin
case index is
when 1 => return "pre-";
when 2 => return "do-";
when 3 => return "post-";
when others => return "";
end case;
end get_prefix;
begin
for phase in Positive range 1 .. 6 loop
for prefix in Positive range 1 .. 3 loop
declare
target : String := get_prefix (prefix) & get_phasestr (phase);
begin
dump_standard_target (target);
dump_opsys_target (target);
end;
end loop;
end loop;
end;
-- TODO: This is not correct, placeholder. rethink.
send (".include " & LAT.Quotation & "/usr/raven/share/mk/raven.mk" & LAT.Quotation);
if write_to_file then
TIO.Close (makefile_handle);
end if;
exception
when others =>
if TIO.Is_Open (makefile_handle) then
TIO.Close (makefile_handle);
end if;
end generator;
end Port_Specification.Makefile;
|
Add support for generating standard and -opsys targets
|
Add support for generating standard and -opsys targets
the -option targets still need to be implemented.
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
de189974db75db57b799e1bbc72087cd4f0e4c35
|
samples/encodes.adb
|
samples/encodes.adb
|
-----------------------------------------------------------------------
-- encodes -- Encodes strings
-- 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.Text_IO;
with Ada.Command_Line;
with Util.Encoders;
procedure Encodes is
use Util.Encoders;
Encode : Boolean := True;
Count : constant Natural := Ada.Command_Line.Argument_Count;
begin
if Count <= 1 then
Ada.Text_IO.Put_Line ("Usage: encodes {encoder} [-d|-e] string...");
Ada.Text_IO.Put_Line ("Encoders: " & Util.Encoders.BASE_64 & ", "
& Util.Encoders.BASE_64_URL & ", "
& Util.Encoders.BASE_16);
return;
end if;
declare
Name : constant String := Ada.Command_Line.Argument (1);
C : constant Encoder := Util.Encoders.Create (Name);
begin
for I in 2 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
begin
if S = "-d" then
Encode := False;
elsif S = "-e" then
Encode := True;
elsif Encode then
Ada.Text_IO.Put_Line ("Encodes " & Name & ": " & C.Encode (S));
else
Ada.Text_IO.Put_Line ("Decodes " & Name & ": " & C.Decode (S));
end if;
end;
end loop;
end;
end Encodes;
|
-----------------------------------------------------------------------
-- encodes -- Encodes strings
-- 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.Text_IO;
with Ada.Command_Line;
with Util.Encoders;
procedure Encodes is
use Util.Encoders;
Encode : Boolean := True;
Count : constant Natural := Ada.Command_Line.Argument_Count;
begin
if Count <= 1 then
Ada.Text_IO.Put_Line ("Usage: encodes {encoder} [-d|-e] string...");
Ada.Text_IO.Put_Line ("Encoders: " & Util.Encoders.BASE_64 & ", "
& Util.Encoders.BASE_64_URL & ", "
& Util.Encoders.BASE_16 & ", "
& Util.Encoders.HASH_SHA1);
return;
end if;
declare
Name : constant String := Ada.Command_Line.Argument (1);
C : constant Encoder := Util.Encoders.Create (Name);
begin
for I in 2 .. Count loop
declare
S : constant String := Ada.Command_Line.Argument (I);
begin
if S = "-d" then
Encode := False;
elsif S = "-e" then
Encode := True;
elsif Encode then
Ada.Text_IO.Put_Line ("Encodes " & Name & ": " & C.Encode (S));
else
Ada.Text_IO.Put_Line ("Decodes " & Name & ": " & C.Decode (S));
end if;
end;
end loop;
end;
end Encodes;
|
Add sha1 encoding
|
Add sha1 encoding
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
05af295d83058a1d5bdec963a7ea248b933a6872
|
src/asf-locales.adb
|
src/asf-locales.adb
|
-----------------------------------------------------------------------
-- asf-locales -- Locale support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Vectors;
with ASF.Contexts.Faces;
with Ada.Strings.Unbounded;
package body ASF.Locales is
use Util.Properties.Bundles;
type Locale_Binding (Len : Natural) is new ASF.Beans.Class_Binding with record
Loader : Loader_Access;
Scope : ASF.Beans.Scope_Type;
Name : String (1 .. Len);
end record;
type Locale_Binding_Access is access all Locale_Binding;
procedure Create (Factory : in Locale_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access);
-- ------------------------------
-- Initialize the locale support by using the configuration properties.
-- Properties matching the pattern: <b>bundle</b>.<i>var-name</i>=<i>bundle-name</i>
-- are used to register bindings linking a facelet variable <i>var-name</i>
-- to the resource bundle <i>bundle-name</i>.
-- ------------------------------
procedure Initialize (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Config : in Util.Properties.Manager'Class) is
Names : Util.Strings.Vectors.Vector;
Dir : constant String := Config.Get ("bundle.dir", "bundles");
begin
Config.Get_Names (Names, "bundle.var.");
Util.Properties.Bundles.Initialize (Fac.Factory, Dir);
for Name of Names loop -- I in Names'Range loop
declare
Value : constant String := Config.Get (Name);
begin
Register (Fac, Beans, Name (Name'First + 11 .. Name'Last), Value);
end;
end loop;
end Initialize;
-- ------------------------------
-- Compute the locale that must be used according to the <b>Accept-Language</b> request
-- header and the application supported locales.
-- ------------------------------
function Calculate_Locale (Fac : in Factory;
Req : in ASF.Requests.Request'Class)
return Util.Locales.Locale is
use Util.Locales;
use type ASF.Requests.Quality_Type;
procedure Process_Locales (Locale : in Util.Locales.Locale;
Quality : in ASF.Requests.Quality_Type);
Found_Locale : Util.Locales.Locale := Fac.Default_Locale;
Found_Quality : ASF.Requests.Quality_Type := 0.0;
procedure Process_Locales (Locale : in Util.Locales.Locale;
Quality : in ASF.Requests.Quality_Type) is
begin
if Found_Quality >= Quality then
return;
end if;
for I in 1 .. Fac.Nb_Locales loop
-- We need a match on the language. The variant/country can be ignored and will
-- be honored by the resource bundle.
if Fac.Locales (I) = Locale
or Get_Language (Fac.Locales (I)) = Get_Language (Locale)
then
Found_Locale := Locale;
Found_Quality := Quality;
return;
end if;
end loop;
end Process_Locales;
begin
if Fac.Nb_Locales > 0 then
Req.Accept_Locales (Process_Locales'Access);
end if;
return Found_Locale;
end Calculate_Locale;
procedure Register (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Name : in String;
Bundle : in String) is
L : constant Locale_Binding_Access := new Locale_Binding (Len => Bundle'Length);
P : ASF.Beans.Parameter_Bean_Ref.Ref;
begin
L.Loader := Fac.Factory'Unchecked_Access;
L.Scope := ASF.Beans.REQUEST_SCOPE;
L.Name := Bundle;
ASF.Beans.Register (Beans, Name, L.all'Access, P);
end Register;
-- Load the resource bundle identified by the <b>Name</b> and for the given
-- <b>Locale</b>.
procedure Load_Bundle (Fac : in out Factory;
Name : in String;
Locale : in String;
Result : out Bundle) is
begin
Load_Bundle (Factory => Fac.Factory,
Locale => Locale,
Name => Name,
Bundle => Result);
end Load_Bundle;
-- ------------------------------
-- Get the list of supported locales for this application.
-- ------------------------------
function Get_Supported_Locales (From : in Factory)
return Util.Locales.Locale_Array is
begin
return From.Locales (1 .. From.Nb_Locales);
end Get_Supported_Locales;
-- ------------------------------
-- Add the locale to the list of supported locales.
-- ------------------------------
procedure Add_Supported_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale) is
begin
Into.Nb_Locales := Into.Nb_Locales + 1;
Into.Locales (Into.Nb_Locales) := Locale;
end Add_Supported_Locale;
-- ------------------------------
-- Get the default locale defined by the application.
-- ------------------------------
function Get_Default_Locale (From : in Factory) return Util.Locales.Locale is
begin
return From.Default_Locale;
end Get_Default_Locale;
-- ------------------------------
-- Set the default locale defined by the application.
-- ------------------------------
procedure Set_Default_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale) is
begin
Into.Default_Locale := Locale;
end Set_Default_Locale;
procedure Create (Factory : in Locale_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access) is
pragma Unreferenced (Name);
use type ASF.Contexts.Faces.Faces_Context_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
B : constant Bundle_Access := new Bundle;
begin
if Context = null then
Load_Bundle (Factory => Factory.Loader.all,
Locale => "en",
Name => Factory.Name,
Bundle => B.all);
else
Load_Bundle (Factory => Factory.Loader.all,
Locale => Util.Locales.To_String (Context.Get_Locale),
Name => Factory.Name,
Bundle => B.all);
end if;
Result := B.all'Access;
end Create;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : Bundle;
Name : String) return Util.Beans.Objects.Object is
Value : constant String := From.Get (Name, Name);
begin
return Util.Beans.Objects.To_Object (Value);
end Get_Value;
end ASF.Locales;
|
-----------------------------------------------------------------------
-- asf-locales -- Locale support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings.Vectors;
with ASF.Contexts.Faces;
with Ada.Strings.Unbounded;
package body ASF.Locales is
use Util.Properties.Bundles;
type Locale_Binding (Len : Natural) is new ASF.Beans.Class_Binding with record
Loader : Loader_Access;
Scope : ASF.Beans.Scope_Type;
Name : String (1 .. Len);
end record;
type Locale_Binding_Access is access all Locale_Binding;
procedure Create (Factory : in Locale_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access);
-- ------------------------------
-- Initialize the locale support by using the configuration properties.
-- Properties matching the pattern: <b>bundle</b>.<i>var-name</i>=<i>bundle-name</i>
-- are used to register bindings linking a facelet variable <i>var-name</i>
-- to the resource bundle <i>bundle-name</i>.
-- ------------------------------
procedure Initialize (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Config : in Util.Properties.Manager'Class) is
Names : Util.Strings.Vectors.Vector;
Dir : constant String := Config.Get ("bundle.dir", "bundles");
begin
Config.Get_Names (Names, "bundle.var.");
Util.Properties.Bundles.Initialize (Fac.Factory, Dir);
for Name of Names loop -- I in Names'Range loop
declare
Value : constant String := Config.Get (Name);
begin
Register (Fac, Beans, Name (Name'First + 11 .. Name'Last), Value);
end;
end loop;
end Initialize;
-- ------------------------------
-- Compute the locale that must be used according to the <b>Accept-Language</b> request
-- header and the application supported locales.
-- ------------------------------
function Calculate_Locale (Fac : in Factory;
Req : in ASF.Requests.Request'Class)
return Util.Locales.Locale is
use Util.Locales;
use type ASF.Requests.Quality_Type;
procedure Process_Locales (Locale : in Util.Locales.Locale;
Quality : in ASF.Requests.Quality_Type);
Found_Locale : Util.Locales.Locale := Fac.Default_Locale;
Found_Quality : ASF.Requests.Quality_Type := 0.0;
procedure Process_Locales (Locale : in Util.Locales.Locale;
Quality : in ASF.Requests.Quality_Type) is
begin
if Found_Quality >= Quality then
return;
end if;
for I in 1 .. Fac.Nb_Locales loop
-- We need a match on the language. The variant/country can be ignored and will
-- be honored by the resource bundle.
if Fac.Locales (I) = Locale
or Get_Language (Fac.Locales (I)) = Get_Language (Locale)
then
Found_Locale := Locale;
Found_Quality := Quality;
return;
end if;
end loop;
end Process_Locales;
begin
if Fac.Nb_Locales > 0 then
Req.Accept_Locales (Process_Locales'Access);
end if;
return Found_Locale;
end Calculate_Locale;
procedure Register (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Name : in String;
Bundle : in String) is
L : constant Locale_Binding_Access := new Locale_Binding (Len => Bundle'Length);
P : ASF.Beans.Parameter_Bean_Ref.Ref;
begin
L.Loader := Fac.Factory'Unchecked_Access;
L.Scope := ASF.Beans.REQUEST_SCOPE;
L.Name := Bundle;
ASF.Beans.Register (Beans, Name, L.all'Access, P);
end Register;
-- Load the resource bundle identified by the <b>Name</b> and for the given
-- <b>Locale</b>.
procedure Load_Bundle (Fac : in out Factory;
Name : in String;
Locale : in String;
Result : out Bundle) is
begin
Load_Bundle (Factory => Fac.Factory,
Locale => Locale,
Name => Name,
Bundle => Result);
end Load_Bundle;
-- ------------------------------
-- Get the list of supported locales for this application.
-- ------------------------------
function Get_Supported_Locales (From : in Factory)
return Util.Locales.Locale_Array is
begin
return From.Locales (1 .. From.Nb_Locales);
end Get_Supported_Locales;
-- ------------------------------
-- Add the locale to the list of supported locales.
-- ------------------------------
procedure Add_Supported_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale) is
begin
Into.Nb_Locales := Into.Nb_Locales + 1;
Into.Locales (Into.Nb_Locales) := Locale;
end Add_Supported_Locale;
-- ------------------------------
-- Get the default locale defined by the application.
-- ------------------------------
function Get_Default_Locale (From : in Factory) return Util.Locales.Locale is
begin
return From.Default_Locale;
end Get_Default_Locale;
-- ------------------------------
-- Set the default locale defined by the application.
-- ------------------------------
procedure Set_Default_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale) is
begin
Into.Default_Locale := Locale;
end Set_Default_Locale;
procedure Create (Factory : in Locale_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access) is
pragma Unreferenced (Name);
use type ASF.Contexts.Faces.Faces_Context_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
B : constant Bundle_Access := new Bundle;
begin
if Context = null then
Load_Bundle (Factory => Factory.Loader.all,
Locale => "en",
Name => Factory.Name,
Bundle => B.all);
else
Load_Bundle (Factory => Factory.Loader.all,
Locale => Util.Locales.To_String (Context.Get_Locale),
Name => Factory.Name,
Bundle => B.all);
end if;
Result := B.all'Access;
end Create;
end ASF.Locales;
|
Remove the Get_Value function because it is already provided by the property manager
|
Remove the Get_Value function because it is already provided by the property manager
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
f0dd76bfc32f66ffa569b85706607af51eb8ab8f
|
src/ado-drivers.adb
|
src/ado-drivers.adb
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.IO_Exceptions;
with ADO.Queries.Loaders;
package body ADO.Drivers is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers");
-- Global configuration properties (loaded by Initialize).
Global_Config : Util.Properties.Manager;
-- ------------------------------
-- Initialize the drivers and the library by reading the property file
-- and configure the runtime with it.
-- ------------------------------
procedure Initialize (Config : in String) is
begin
Log.Info ("Initialize using property file {0}", Config);
begin
Util.Properties.Load_Properties (Global_Config, Config);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Configuration file '{0}' does not exist", Config);
end;
Initialize (Global_Config);
end Initialize;
-- ------------------------------
-- Initialize the drivers and the library and configure the runtime with the given properties.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager'Class) is
begin
Global_Config := Util.Properties.Manager (Config);
-- Configure the XML query loader.
ADO.Queries.Loaders.Initialize (Global_Config.Get ("ado.queries.paths", ".;db"),
Global_Config.Get ("ado.queries.load", "false") = "true");
end Initialize;
-- ------------------------------
-- Get the global configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
-- ------------------------------
function Get_Config (Name : in String;
Default : in String := "") return String is
begin
return Global_Config.Get (Name, Default);
end Get_Config;
end ADO.Drivers;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.IO_Exceptions;
with ADO.Queries.Loaders;
package body ADO.Drivers is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers");
-- Global configuration properties (loaded by Initialize).
Global_Config : Util.Properties.Manager;
-- ------------------------------
-- Initialize the drivers and the library by reading the property file
-- and configure the runtime with it.
-- ------------------------------
procedure Initialize (Config : in String) is
begin
Log.Info ("Initialize using property file {0}", Config);
begin
Util.Properties.Load_Properties (Global_Config, Config);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Configuration file '{0}' does not exist", Config);
end;
Initialize (Global_Config);
end Initialize;
-- ------------------------------
-- Initialize the drivers and the library and configure the runtime with the given properties.
-- ------------------------------
procedure Initialize (Config : in Util.Properties.Manager'Class) is
begin
Global_Config := Util.Properties.Manager (Config);
-- Configure the XML query loader.
ADO.Queries.Loaders.Initialize (Global_Config.Get ("ado.queries.paths", ".;db"),
Global_Config.Get ("ado.queries.load", "false") = "true");
ADO.Drivers.Initialize;
end Initialize;
-- ------------------------------
-- Get the global configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
-- ------------------------------
function Get_Config (Name : in String;
Default : in String := "") return String is
begin
return Global_Config.Get (Name, Default);
end Get_Config;
-- Initialize the drivers which are available.
procedure Initialize is separate;
end ADO.Drivers;
|
Call the initialize procedure that is now separate (as in previous ADO versions)
|
Call the initialize procedure that is now separate (as in previous ADO versions)
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
a33f6075a8a62e4fbb16fe131e3f84ff60690bb7
|
awa/awaunit/awa-tests-helpers-users.adb
|
awa/awaunit/awa-tests-helpers-users.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- 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.Unchecked_Deallocation;
with Util.Tests;
with Util.Log.Loggers;
with AWA.Applications;
with AWA.Tests;
with AWA.Users.Modules;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Tests.Helpers.Users is
use AWA.Users.Services;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users");
-- ------------------------------
-- Initialize the service context.
-- ------------------------------
procedure Initialize (Principal : in out Test_User) is
begin
-- Setup the service context.
Principal.Context.Set_Context (AWA.Tests.Get_Application, null);
if Principal.Manager = null then
Principal.Manager := AWA.Users.Modules.Get_User_Manager;
if Principal.Manager = null then
Log.Error ("There is no User_Manager in the application.");
end if;
end if;
end Initialize;
-- ------------------------------
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
-- ------------------------------
procedure Create_User (Principal : in out Test_User;
Email : in String) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the user
Query.Set_Join ("inner join awa_email e on e.user_id = o.id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Principal.User.Find (DB, Query, Found);
if not Found then
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
else
Principal.Manager.Authenticate (Email => Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
end if;
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Create a test user for a new test and get an open session.
-- ------------------------------
procedure Create_User (Principal : in out Test_User) is
Key : AWA.Users.Models.Access_Key_Ref;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
begin
Initialize (Principal);
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Find the access key associated with a user (if any).
-- ------------------------------
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the access key
Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Key.Find (DB, Query, Found);
if not Found then
Log.Error ("Cannot find access key for email {0}", Email);
end if;
end Find_Access_Key;
-- ------------------------------
-- Login a user and create a session
-- ------------------------------
procedure Login (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Authenticate (Email => Principal.Email.Get_Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Login;
-- ------------------------------
-- Logout the user and closes the current session.
-- ------------------------------
procedure Logout (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Close_Session (Principal.Session.Get_Id, True);
end Logout;
-- Simulate a user login in the given service context.
procedure Login (Context : in out AWA.Services.Contexts.Service_Context;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String) is
User : Test_User;
Principal : AWA.Users.Principals.Principal_Access;
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Create_User (User, Email);
Principal := AWA.Users.Principals.Create (User.User, User.Session);
Context.Set_Context (App, Principal);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => Principal.all'Access);
end Login;
overriding
procedure Finalize (Principal : in out Test_User) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class,
Name => AWA.Users.Principals.Principal_Access);
begin
Free (Principal.Principal);
end Finalize;
end AWA.Tests.Helpers.Users;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- 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.Unchecked_Deallocation;
with Util.Tests;
with Util.Log.Loggers;
with AWA.Applications;
with AWA.Tests;
with AWA.Users.Modules;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Tests.Helpers.Users is
use AWA.Users.Services;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users");
-- ------------------------------
-- Initialize the service context.
-- ------------------------------
procedure Initialize (Principal : in out Test_User) is
begin
-- Setup the service context.
Principal.Context.Set_Context (AWA.Tests.Get_Application, null);
if Principal.Manager = null then
Principal.Manager := AWA.Users.Modules.Get_User_Manager;
if Principal.Manager = null then
Log.Error ("There is no User_Manager in the application.");
end if;
end if;
end Initialize;
-- ------------------------------
-- Create a test user associated with the given email address.
-- Get an open session for that user. If the user already exists, no error is reported.
-- ------------------------------
procedure Create_User (Principal : in out Test_User;
Email : in String) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the user
Query.Set_Join ("inner join awa_email e on e.user_id = o.id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Principal.User.Find (DB, Query, Found);
if not Found then
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
else
Principal.Manager.Authenticate (Email => Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
end if;
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Create a test user for a new test and get an open session.
-- ------------------------------
procedure Create_User (Principal : in out Test_User) is
Key : AWA.Users.Models.Access_Key_Ref;
Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com";
begin
Initialize (Principal);
Principal.User.Set_First_Name ("Joe");
Principal.User.Set_Last_Name ("Pot");
Principal.User.Set_Password ("admin");
Principal.Email.Set_Email (Email);
Principal.Manager.Create_User (Principal.User, Principal.Email);
Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Create_User;
-- ------------------------------
-- Find the access key associated with a user (if any).
-- ------------------------------
procedure Find_Access_Key (Principal : in out Test_User;
Email : in String;
Key : in out AWA.Users.Models.Access_Key_Ref) is
DB : ADO.Sessions.Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Initialize (Principal);
DB := Principal.Manager.Get_Session;
-- Find the access key
Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id");
Query.Set_Filter ("e.email = ?");
Query.Bind_Param (1, Email);
Key.Find (DB, Query, Found);
if not Found then
Log.Error ("Cannot find access key for email {0}", Email);
end if;
end Find_Access_Key;
-- ------------------------------
-- Login a user and create a session
-- ------------------------------
procedure Login (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Authenticate (Email => Principal.Email.Get_Email,
Password => "admin",
IpAddr => "192.168.1.1",
Principal => Principal.Principal);
Principal.User := Principal.Principal.Get_User;
Principal.Session := Principal.Principal.Get_Session;
end Login;
-- ------------------------------
-- Logout the user and closes the current session.
-- ------------------------------
procedure Logout (Principal : in out Test_User) is
begin
Initialize (Principal);
Principal.Manager.Close_Session (Principal.Session.Get_Id, True);
end Logout;
-- ------------------------------
-- Simulate a user login in the given service context.
-- ------------------------------
procedure Login (Context : in out AWA.Services.Contexts.Service_Context;
Sec_Context : in out Security.Contexts.Security_Context;
Email : in String) is
User : Test_User;
Principal : AWA.Users.Principals.Principal_Access;
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Create_User (User, Email);
Principal := AWA.Users.Principals.Create (User.User, User.Session);
Context.Set_Context (App, Principal);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => Principal.all'Access);
end Login;
-- ------------------------------
-- Setup the context and security context to simulate an anonymous user.
-- ------------------------------
procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context;
Sec_Context : in out Security.Contexts.Security_Context) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
begin
AWA.Tests.Set_Application_Context;
Context.Set_Context (App, null);
Sec_Context.Set_Context (Manager => App.Get_Security_Manager,
Principal => null);
end Anonymous;
overriding
procedure Finalize (Principal : in out Test_User) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class,
Name => AWA.Users.Principals.Principal_Access);
begin
Free (Principal.Principal);
end Finalize;
end AWA.Tests.Helpers.Users;
|
Implement the Anonymous procedure to simulate anonymous users
|
Implement the Anonymous procedure to simulate anonymous users
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
29c991d5a3c652a2d1c55a7b113935abe337ffff
|
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.Roles;
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;
-- ------------------------------
-- 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.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.PERMISSION_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 Util.Log.Loggers;
with Security.Policies.Roles;
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;
-- ------------------------------
-- 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.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;
|
Fix the Delete_Permission operation
|
Fix the Delete_Permission operation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1ecbb4574e48f3b222b4e9a1f926dc4593d0567d
|
src/babel-streams-files.adb
|
src/babel-streams-files.adb
|
-----------------------------------------------------------------------
-- babel-streams-files -- Local file stream management
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with System.OS_Constants;
with Ada.Streams;
with Ada.Directories;
with Ada.IO_Exceptions;
with Util.Systems.Os;
with Util.Systems.Constants;
package body Babel.Streams.Files is
use type Interfaces.C.int;
function Errno return Integer;
pragma Import (C, errno, "__get_errno");
-- ------------------------------
-- Open the local file for reading and use the given buffer for the Read operation.
-- ------------------------------
procedure Open (Stream : in out Stream_Type;
Path : in String;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Fd : Util.Systems.Os.File_Type;
begin
Fd := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_RDONLY,
Mode => 0);
Interfaces.C.Strings.Free (Name);
Stream.Buffer := Buffer;
Stream.File.Initialize (File => Fd);
end Open;
-- ------------------------------
-- Create a file and prepare for the Write operation.
-- ------------------------------
procedure Create (Stream : in out Stream_Type;
Path : in String;
Mode : in Util.Systems.Types.mode_t) is
use type Util.Systems.Os.File_Type;
use Util.Systems.Os;
use type Interfaces.C.int;
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
File : Util.Systems.Os.File_Type;
begin
File := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_WRONLY
+ Util.Systems.Constants.O_CREAT
+ Util.Systems.Constants.O_TRUNC,
Mode => Mode);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, Mode);
end if;
end if;
Interfaces.C.Strings.Free (Name);
Stream.Buffer := null;
Stream.File.Initialize (File => File);
if File < 0 then
raise Ada.IO_Exceptions.Name_Error with "Cannot create '" & Path & "'";
end if;
end Create;
-- ------------------------------
-- Read the data stream as much as possible and return the result in a buffer.
-- The buffer is owned by the stream and need not be released. The same buffer may
-- or may not be returned by the next <tt>Read</tt> operation.
-- A null buffer is returned when the end of the data stream is reached.
-- ------------------------------
overriding
procedure Read (Stream : in out Stream_Type;
Buffer : out Babel.Files.Buffers.Buffer_Access) is
use type Ada.Streams.Stream_Element_Offset;
begin
if Stream.Eof then
Buffer := null;
else
Stream.File.Read (Stream.Buffer.Data, Stream.Buffer.Last);
if Stream.Buffer.Last < Stream.Buffer.Data'First then
Buffer := null;
else
Buffer := Stream.Buffer;
end if;
Stream.Eof := Stream.Buffer.Last < Stream.Buffer.Data'Last;
end if;
end Read;
-- ------------------------------
-- Write the buffer in the data stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
begin
Stream.File.Write (Buffer.Data (Buffer.Data'First .. Buffer.Last));
end Write;
-- ------------------------------
-- Close the data stream.
-- ------------------------------
overriding
procedure Close (Stream : in out Stream_Type) is
begin
Stream.File.Close;
end Close;
-- ------------------------------
-- Prepare to read again the data stream from the beginning.
-- ------------------------------
overriding
procedure Rewind (Stream : in out Stream_Type) is
begin
Stream.File.Seek (0, Util.Systems.Types.SEEK_SET);
Stream.Eof := False;
end Rewind;
end Babel.Streams.Files;
|
-----------------------------------------------------------------------
-- babel-streams-files -- Local file stream management
-- Copyright (C) 2014, 2015, 2016 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces.C.Strings;
with System.OS_Constants;
with Ada.Streams;
with Ada.Directories;
with Ada.IO_Exceptions;
with Util.Systems.Os;
with Util.Systems.Constants;
package body Babel.Streams.Files is
use type Interfaces.C.int;
-- ------------------------------
-- Open the local file for reading and use the given buffer for the Read operation.
-- ------------------------------
procedure Open (Stream : in out Stream_Type;
Path : in String;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
Fd : Util.Systems.Os.File_Type;
begin
Fd := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_RDONLY,
Mode => 0);
Interfaces.C.Strings.Free (Name);
Stream.Buffer := Buffer;
Stream.File.Initialize (File => Fd);
end Open;
-- ------------------------------
-- Create a file and prepare for the Write operation.
-- ------------------------------
procedure Create (Stream : in out Stream_Type;
Path : in String;
Mode : in Util.Systems.Types.mode_t) is
use type Util.Systems.Os.File_Type;
use Util.Systems.Os;
use type Interfaces.C.int;
Name : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String (Path);
File : Util.Systems.Os.File_Type;
begin
File := Util.Systems.Os.Sys_Open (Path => Name,
Flags => Util.Systems.Constants.O_WRONLY
+ Util.Systems.Constants.O_CREAT
+ Util.Systems.Constants.O_TRUNC,
Mode => Mode);
if File < 0 then
if Errno = System.OS_Constants.ENOENT then
declare
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Ada.Directories.Create_Path (Dir);
end;
File := Util.Systems.Os.Sys_Open (Name, O_CREAT + O_WRONLY, Mode);
end if;
end if;
Interfaces.C.Strings.Free (Name);
Stream.Buffer := null;
Stream.File.Initialize (File => File);
if File < 0 then
raise Ada.IO_Exceptions.Name_Error with "Cannot create '" & Path & "'";
end if;
end Create;
-- ------------------------------
-- Read the data stream as much as possible and return the result in a buffer.
-- The buffer is owned by the stream and need not be released. The same buffer may
-- or may not be returned by the next <tt>Read</tt> operation.
-- A null buffer is returned when the end of the data stream is reached.
-- ------------------------------
overriding
procedure Read (Stream : in out Stream_Type;
Buffer : out Babel.Files.Buffers.Buffer_Access) is
use type Ada.Streams.Stream_Element_Offset;
begin
if Stream.Eof then
Buffer := null;
else
Stream.File.Read (Stream.Buffer.Data, Stream.Buffer.Last);
if Stream.Buffer.Last < Stream.Buffer.Data'First then
Buffer := null;
else
Buffer := Stream.Buffer;
end if;
Stream.Eof := Stream.Buffer.Last < Stream.Buffer.Data'Last;
end if;
end Read;
-- ------------------------------
-- Write the buffer in the data stream.
-- ------------------------------
overriding
procedure Write (Stream : in out Stream_Type;
Buffer : in Babel.Files.Buffers.Buffer_Access) is
begin
Stream.File.Write (Buffer.Data (Buffer.Data'First .. Buffer.Last));
end Write;
-- ------------------------------
-- Close the data stream.
-- ------------------------------
overriding
procedure Close (Stream : in out Stream_Type) is
begin
Stream.File.Close;
end Close;
-- ------------------------------
-- Prepare to read again the data stream from the beginning.
-- ------------------------------
overriding
procedure Rewind (Stream : in out Stream_Type) is
begin
Stream.File.Seek (0, Util.Systems.Types.SEEK_SET);
Stream.Eof := False;
end Rewind;
end Babel.Streams.Files;
|
Remove declaration of Errno function
|
Remove declaration of Errno function
|
Ada
|
apache-2.0
|
stcarrez/babel
|
bc61f8f4bc22ad5256a0af9d471184e237ddc475
|
regtests/ado-drivers-tests.adb
|
regtests/ado-drivers-tests.adb
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- 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.Test_Caller;
with ADO.Drivers.Connections;
package body ADO.Drivers.Tests is
use ADO.Drivers.Connections;
package Caller is new Util.Test_Caller (Test, "ADO.Drivers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config",
Test_Get_Config'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Get_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index",
Test_Get_Driver_Index'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Load_Invalid_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection",
Test_Set_Connection'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)",
Test_Set_Connection_Error'Access);
end Add_Tests;
-- ------------------------------
-- Test the Get_Config operation.
-- ------------------------------
procedure Test_Get_Config (T : in out Test) is
begin
T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0,
"The Get_Config operation returned no value for the test database");
end Test_Get_Config;
-- ------------------------------
-- Test the Get_Driver operation.
-- ------------------------------
procedure Test_Get_Driver (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null,
"No database driver was found!");
end Test_Get_Driver;
-- ------------------------------
-- Test loading some invalid database driver.
-- ------------------------------
procedure Test_Load_Invalid_Driver (T : in out Test) is
Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid");
begin
T.Assert (Invalid_Driver = null,
"The Get_Driver operation must return null for invalid drivers");
end Test_Load_Invalid_Driver;
-- ------------------------------
-- Test the Get_Driver_Index operation.
-- ------------------------------
procedure Test_Get_Driver_Index (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
if Mysql_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Sqlite_Driver /= null then
T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Mysql_Driver /= null and Sqlite_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index,
"Two drivers must have different driver indexes");
end if;
end Test_Get_Driver_Index;
-- ------------------------------
-- Test the Set_Connection procedure.
-- ------------------------------
procedure Test_Set_Connection (T : in out Test) is
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String);
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String) is
Controller : ADO.Drivers.Connections.Configuration;
begin
Controller.Set_Connection (URI);
Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI);
Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI);
Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI);
end Check;
begin
Check ("mysql://test:3306/db", "test", 3306, "db");
Check ("sqlite:///test.db", "", 0, "test.db");
end Test_Set_Connection;
-- ------------------------------
-- Test the Set_Connection procedure with several error cases.
-- ------------------------------
procedure Test_Set_Connection_Error (T : in out Test) is
procedure Check_Invalid_Connection (URI : in String);
Controller : ADO.Drivers.Connections.Configuration;
procedure Check_Invalid_Connection (URI : in String) is
begin
Controller.Set_Connection (URI);
T.Fail ("No Connection_Error exception raised for " & URI);
exception
when Connection_Error =>
null;
end Check_Invalid_Connection;
begin
Check_Invalid_Connection ("");
Check_Invalid_Connection ("http://");
Check_Invalid_Connection ("mysql://");
Check_Invalid_Connection ("sqlite://");
Check_Invalid_Connection ("mysql://:toto/");
Check_Invalid_Connection ("sqlite://:toto/");
end Test_Set_Connection_Error;
end ADO.Drivers.Tests;
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- 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.Test_Caller;
with ADO.Drivers.Connections;
package body ADO.Drivers.Tests is
use ADO.Drivers.Connections;
package Caller is new Util.Test_Caller (Test, "ADO.Drivers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config",
Test_Get_Config'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Get_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index",
Test_Get_Driver_Index'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver",
Test_Load_Invalid_Driver'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection",
Test_Set_Connection'Access);
Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)",
Test_Set_Connection_Error'Access);
end Add_Tests;
-- ------------------------------
-- Test the Get_Config operation.
-- ------------------------------
procedure Test_Get_Config (T : in out Test) is
begin
T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0,
"The Get_Config operation returned no value for the test database");
end Test_Get_Config;
-- ------------------------------
-- Test the Get_Driver operation.
-- ------------------------------
procedure Test_Get_Driver (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null,
"No database driver was found!");
end Test_Get_Driver;
-- ------------------------------
-- Test loading some invalid database driver.
-- ------------------------------
procedure Test_Load_Invalid_Driver (T : in out Test) is
Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid");
begin
T.Assert (Invalid_Driver = null,
"The Get_Driver operation must return null for invalid drivers");
end Test_Load_Invalid_Driver;
-- ------------------------------
-- Test the Get_Driver_Index operation.
-- ------------------------------
procedure Test_Get_Driver_Index (T : in out Test) is
Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql");
Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite");
begin
if Mysql_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Sqlite_Driver /= null then
T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive");
end if;
if Mysql_Driver /= null and Sqlite_Driver /= null then
T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index,
"Two drivers must have different driver indexes");
end if;
end Test_Get_Driver_Index;
-- ------------------------------
-- Test the Set_Connection procedure.
-- ------------------------------
procedure Test_Set_Connection (T : in out Test) is
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String);
procedure Check (URI : in String;
Server : in String;
Port : in Integer;
Database : in String) is
Controller : ADO.Drivers.Connections.Configuration;
begin
Controller.Set_Connection (URI);
Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI);
Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI);
Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI);
Controller.Set_Property ("password", "test");
Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"),
"Invalid 'password' property for " & URI);
end Check;
begin
Check ("mysql://test:3306/db", "test", 3306, "db");
Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2");
Check ("sqlite:///test.db", "", 0, "test.db");
Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db");
end Test_Set_Connection;
-- ------------------------------
-- Test the Set_Connection procedure with several error cases.
-- ------------------------------
procedure Test_Set_Connection_Error (T : in out Test) is
procedure Check_Invalid_Connection (URI : in String);
Controller : ADO.Drivers.Connections.Configuration;
procedure Check_Invalid_Connection (URI : in String) is
begin
Controller.Set_Connection (URI);
T.Fail ("No Connection_Error exception raised for " & URI);
exception
when Connection_Error =>
null;
end Check_Invalid_Connection;
begin
Check_Invalid_Connection ("");
Check_Invalid_Connection ("http://");
Check_Invalid_Connection ("mysql://");
Check_Invalid_Connection ("sqlite://");
Check_Invalid_Connection ("mysql://:toto/");
Check_Invalid_Connection ("sqlite://:toto/");
end Test_Set_Connection_Error;
end ADO.Drivers.Tests;
|
Add more parsing for connection URI properties
|
Add more parsing for connection URI properties
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
cac8a1769b6440b1496e96db2c0bd6989a3ffa9f
|
src/ado-sessions-factory.adb
|
src/ado-sessions-factory.adb
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- 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 ADO.Sequences.Hilo;
with Ada.Unchecked_Deallocation;
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
package body ADO.Sessions.Factory is
use ADO.Databases;
-- ------------------------------
-- Open a session
-- ------------------------------
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session) is
S : constant Session_Record_Access := new Session_Record;
DB : constant Master_Connection'Class := Factory.Source.Get_Connection;
begin
S.Database := Master_Connection (DB);
S.Entities := Factory.Entities;
Database.Impl := S;
end Open_Session;
-- ------------------------------
-- Get a read-only session from the factory.
-- ------------------------------
function Get_Session (Factory : in Session_Factory) return Session is
R : Session;
S : constant Session_Record_Access := new Session_Record;
DB : constant Master_Connection'Class := Factory.Source.Get_Connection;
begin
S.Database := Master_Connection (DB);
S.Entities := Factory.Entities;
R.Impl := S;
return R;
end Get_Session;
-- ------------------------------
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
-- ------------------------------
function Get_Session (Proxy : in Session_Proxy_Access) return Session is
R : Session;
begin
if Proxy = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
if Proxy.Session = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
R.Impl := Proxy.Session;
R.Impl.Counter := R.Impl.Counter + 1;
return R;
end Get_Session;
-- ------------------------------
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
-- ------------------------------
function Get_Session (Proxy : in Session_Record_Access) return Session is
R : Session;
begin
if Proxy = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
-- if Proxy.Session = null then
-- raise ADO.Objects.SESSION_EXPIRED;
-- end if;
R.Impl := Proxy;
R.Impl.Counter := R.Impl.Counter + 1;
return R;
end Get_Session;
-- ------------------------------
-- Get a read-write session from the factory.
-- ------------------------------
function Get_Master_Session (Factory : in Session_Factory) return Master_Session is
R : Master_Session;
S : constant Session_Record_Access := new Session_Record;
DB : constant Master_Connection'Class := Factory.Source.Get_Connection;
begin
S.Database := Master_Connection (DB);
S.Entities := Factory.Entities;
R.Impl := S;
R.Sequences := Factory.Sequences;
return R;
end Get_Master_Session;
-- ------------------------------
-- Open a session
-- ------------------------------
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session) is
begin
null;
end Open_Session;
-- ------------------------------
-- Initialize the sequence factory associated with the session factory.
-- ------------------------------
procedure Initialize_Sequences (Factory : in out Session_Factory) is
use ADO.Sequences;
begin
Factory.Sequences := new ADO.Sequences.Factory;
Set_Default_Generator (Factory.Sequences.all,
ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unrestricted_Access);
end Initialize_Sequences;
-- ------------------------------
-- Create the session factory to connect to the database represented
-- by the data source.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
Source : in ADO.Databases.DataSource) is
begin
Factory.Source := Source;
Factory.Entities := Factory.Entity_Cache'Unchecked_Access;
Initialize_Sequences (Factory);
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S);
end;
end Create;
-- ------------------------------
-- Create the session factory to connect to the database identified
-- by the URI.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
URI : in String) is
begin
Factory.Source.Set_Connection (URI);
Factory.Entities := Factory.Entity_Cache'Unchecked_Access;
Initialize_Sequences (Factory);
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S);
end;
end Create;
-- ------------------------------
-- Finalize and release the factory
-- ------------------------------
overriding
procedure Finalize (Factory : in out Session_Factory) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => ADO.Sequences.Factory,
Name => ADO.Sequences.Factory_Access);
Seq : ADO.Sequences.Factory_Access;
begin
if Factory.Sequences /= null then
Seq := Factory.Sequences.all'Access;
Free (Seq);
Factory.Sequences := null;
end if;
end Finalize;
end ADO.Sessions.Factory;
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- 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 ADO.Sequences.Hilo;
with Ada.Unchecked_Deallocation;
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
package body ADO.Sessions.Factory is
use ADO.Databases;
-- ------------------------------
-- Open a session
-- ------------------------------
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session) is
S : constant Session_Record_Access := new Session_Record;
DB : constant Master_Connection'Class := Factory.Source.Get_Connection;
begin
S.Database := Master_Connection (DB);
S.Entities := Factory.Entities;
Database.Impl := S;
end Open_Session;
-- ------------------------------
-- Get a read-only session from the factory.
-- ------------------------------
function Get_Session (Factory : in Session_Factory) return Session is
R : Session;
S : constant Session_Record_Access := new Session_Record;
DB : constant Master_Connection'Class := Factory.Source.Get_Connection;
begin
S.Database := Master_Connection (DB);
S.Entities := Factory.Entities;
R.Impl := S;
return R;
end Get_Session;
-- ------------------------------
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
-- ------------------------------
function Get_Session (Proxy : in Session_Proxy_Access) return Session is
R : Session;
begin
if Proxy = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
if Proxy.Session = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
R.Impl := Proxy.Session;
R.Impl.Counter := R.Impl.Counter + 1;
return R;
end Get_Session;
-- ------------------------------
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
-- ------------------------------
function Get_Session (Proxy : in Session_Record_Access) return Session is
R : Session;
begin
if Proxy = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
-- if Proxy.Session = null then
-- raise ADO.Objects.SESSION_EXPIRED;
-- end if;
R.Impl := Proxy;
R.Impl.Counter := R.Impl.Counter + 1;
return R;
end Get_Session;
-- ------------------------------
-- Get a read-write session from the factory.
-- ------------------------------
function Get_Master_Session (Factory : in Session_Factory) return Master_Session is
R : Master_Session;
S : constant Session_Record_Access := new Session_Record;
DB : constant Master_Connection'Class := Factory.Source.Get_Connection;
begin
S.Database := Master_Connection (DB);
S.Entities := Factory.Entities;
R.Impl := S;
R.Sequences := Factory.Sequences;
return R;
end Get_Master_Session;
-- ------------------------------
-- Open a session
-- ------------------------------
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session) is
begin
null;
end Open_Session;
-- ------------------------------
-- Initialize the sequence factory associated with the session factory.
-- ------------------------------
procedure Initialize_Sequences (Factory : in out Session_Factory) is
use ADO.Sequences;
begin
Factory.Sequences := new ADO.Sequences.Factory;
Set_Default_Generator (Factory.Sequences.all,
ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unrestricted_Access);
end Initialize_Sequences;
-- ------------------------------
-- Create the session factory to connect to the database represented
-- by the data source.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
Source : in ADO.Databases.DataSource) is
begin
Factory.Source := Source;
Factory.Entities := Factory.Entity_Cache'Unchecked_Access;
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S);
end;
end if;
end Create;
-- ------------------------------
-- Create the session factory to connect to the database identified
-- by the URI.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
URI : in String) is
begin
Factory.Source.Set_Connection (URI);
Factory.Entities := Factory.Entity_Cache'Unchecked_Access;
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S);
end;
end if;
end Create;
-- ------------------------------
-- Finalize and release the factory
-- ------------------------------
overriding
procedure Finalize (Factory : in out Session_Factory) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => ADO.Sequences.Factory,
Name => ADO.Sequences.Factory_Access);
Seq : ADO.Sequences.Factory_Access;
begin
if Factory.Sequences /= null then
Seq := Factory.Sequences.all'Access;
Free (Seq);
Factory.Sequences := null;
end if;
end Finalize;
end ADO.Sessions.Factory;
|
Load the database entities only if we have a database
|
Load the database entities only if we have a database
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
b0b0a1e95284bc8d72ead1721d259cdd51670d17
|
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 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;
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.
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;
|
Make the Permission type not abstract
|
Make the Permission type not abstract
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
2f01beae3af138291272844a90a31cf699053dfc
|
regtests/util-concurrent-tests.ads
|
regtests/util-concurrent-tests.ads
|
-----------------------------------------------------------------------
-- concurrency.tests -- Unit tests for concurrency package
-- 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.Concurrent.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Increment (T : in out Test);
procedure Test_Decrement (T : in out Test);
procedure Test_Decrement_And_Test (T : in out Test);
procedure Test_Copy (T : in out Test);
-- Test concurrent pool
procedure Test_Pool (T : in out Test);
-- Test concurrent pool
procedure Test_Concurrent_Pool (T : in out Test);
-- Test fifo.
procedure Test_Fifo (T : in out Test);
-- Test concurrent aspects of fifo.
procedure Test_Concurrent_Fifo (T : in out Test);
-- Test concurrent arrays.
procedure Test_Array (T : in out Test);
end Util.Concurrent.Tests;
|
-----------------------------------------------------------------------
-- concurrency.tests -- Unit tests for concurrency package
-- Copyright (C) 2009, 2010, 2011, 2012, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Concurrent.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Increment (T : in out Test);
procedure Test_Decrement (T : in out Test);
procedure Test_Decrement_And_Test (T : in out Test);
procedure Test_Copy (T : in out Test);
-- Test concurrent pool
procedure Test_Pool (T : in out Test);
-- Test concurrent pool
procedure Test_Concurrent_Pool (T : in out Test);
-- Test fifo.
procedure Test_Fifo (T : in out Test);
-- Test concurrent aspects of fifo.
procedure Test_Concurrent_Fifo (T : in out Test);
-- Test concurrent arrays.
procedure Test_Array (T : in out Test);
-- Test concurrent sequences.
procedure Test_Concurrent_Sequences (T : in out Test);
end Util.Concurrent.Tests;
|
Declare Test_Concurrent_Sequences procedure to test the sequences
|
Declare Test_Concurrent_Sequences procedure to test the sequences
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d721cbfd21bc7c76c809adccb3832cb373f19db3
|
src/ado-objects.adb
|
src/ado-objects.adb
|
-----------------------------------------------------------------------
-- ADO Objects -- Database objects
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
package body ADO.Objects is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Objects");
-- ------------------------------
-- Compute the hash of the object key.
-- ------------------------------
function Hash (Key : Object_Key) return Ada.Containers.Hash_Type is
Result : Ada.Containers.Hash_Type;
begin
-- @todo SCz 2010-08-03: hash on the object type/class/table
case Key.Of_Type is
when KEY_INTEGER =>
Result := Ada.Containers.Hash_Type (Key.Id);
when KEY_STRING =>
Result := 0;
end case;
return Result;
end Hash;
-- ------------------------------
-- Compare whether the two objects pointed to by Left and Right have the same
-- object key.
-- ------------------------------
function Equivalent_Elements (Left, Right : Object_Key)
return Boolean is
use Ada.Strings.Unbounded;
begin
if Left.Of_Type /= Right.Of_Type then
return False;
end if;
case Left.Of_Type is
when KEY_INTEGER =>
return Left.Id = Right.Id;
when KEY_STRING =>
return Left.Str = Right.Str;
end case;
end Equivalent_Elements;
procedure Adjust (Object : in out Object_Ref) is
begin
if Object.Object /= null then
Util.Concurrent.Counters.Increment (Object.Object.Counter);
end if;
end Adjust;
procedure Finalize (Object : in out Object_Ref) is
Is_Zero : Boolean;
begin
if Object.Object /= null then
Util.Concurrent.Counters.Decrement (Object.Object.Counter, Is_Zero);
if Is_Zero then
Destroy (Object.Object);
Object.Object := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Mark the field identified by <b>Field</b> as modified.
-- ------------------------------
procedure Set_Field (Object : in out Object_Ref'Class;
Field : in Positive) is
begin
if Object.Object = null then
Object.Allocate;
end if;
Object.Object.Modified (Field) := True;
end Set_Field;
-- ------------------------------
-- Check whether this object is initialized or not.
-- ------------------------------
function Is_Null (Object : in Object_Ref'Class) return Boolean is
begin
return Object.Object = null;
end Is_Null;
-- ------------------------------
-- Internal method to get the object record instance.
-- ------------------------------
function Get_Object (Ref : in Object_Ref'Class) return Object_Record_Access is
begin
return Ref.Object;
end Get_Object;
-- ------------------------------
-- Check if the two objects are the same database objects.
-- The comparison is only made on the primary key.
-- Returns true if the two objects have the same primary key.
-- ------------------------------
function "=" (Left : Object_Ref'Class; Right : Object_Ref'Class) return Boolean is
begin
-- Same target object
if Left.Object = Right.Object then
return True;
end if;
-- One of the target object is null
if Left.Object = null or Right.Object = null then
return False;
end if;
return Left.Object.Key = Right.Object.Key;
end "=";
procedure Set_Object (Ref : in out Object_Ref'Class;
Object : in Object_Record_Access) is
Is_Zero : Boolean;
begin
if Ref.Object /= null and Ref.Object /= Object then
Util.Concurrent.Counters.Decrement (Ref.Object.Counter, Is_Zero);
if Is_Zero then
Destroy (Ref.Object);
end if;
end if;
Ref.Object := Object;
end Set_Object;
-- ------------------------------
-- Get the object key
-- ------------------------------
function Get_Id (Ref : in Object_Record'Class) return Object_Key is
begin
return Ref.Key;
end Get_Id;
-- ------------------------------
-- Check if this is a new object.
-- Returns True if an insert is necessary to persist this object.
-- ------------------------------
function Is_Created (Ref : in Object_Record'Class) return Boolean is
begin
return Ref.Is_Created;
end Is_Created;
-- ------------------------------
-- Mark the object as created in the database.
-- ------------------------------
procedure Set_Created (Ref : in out Object_Record'Class) is
begin
Ref.Is_Created := True;
end Set_Created;
-- ------------------------------
-- Check if the field at position <b>Field</b> was modified.
-- ------------------------------
function Is_Modified (Ref : in Object_Record'Class;
Field : in Positive) return Boolean is
begin
return Ref.Modified (Field);
end Is_Modified;
-- ------------------------------
-- Clear the modification flag associated with the field at
-- position <b>Field</b>.
-- ------------------------------
procedure Clear_Modified (Ref : in out Object_Record'Class;
Field : in Positive) is
begin
Ref.Modified (Field) := False;
end Clear_Modified;
end ADO.Objects;
|
-----------------------------------------------------------------------
-- ADO Objects -- Database objects
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
package body ADO.Objects is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Objects");
-- ------------------------------
-- Compute the hash of the object key.
-- ------------------------------
function Hash (Key : Object_Key) return Ada.Containers.Hash_Type is
Result : Ada.Containers.Hash_Type;
begin
-- @todo SCz 2010-08-03: hash on the object type/class/table
case Key.Of_Type is
when KEY_INTEGER =>
Result := Ada.Containers.Hash_Type (Key.Id);
when KEY_STRING =>
Result := 0;
end case;
return Result;
end Hash;
-- ------------------------------
-- Compare whether the two objects pointed to by Left and Right have the same
-- object key.
-- ------------------------------
function Equivalent_Elements (Left, Right : Object_Key)
return Boolean is
use Ada.Strings.Unbounded;
begin
if Left.Of_Type /= Right.Of_Type then
return False;
end if;
case Left.Of_Type is
when KEY_INTEGER =>
return Left.Id = Right.Id;
when KEY_STRING =>
return Left.Str = Right.Str;
end case;
end Equivalent_Elements;
-- ------------------------------
-- Increment the reference counter when an object is copied
-- ------------------------------
procedure Adjust (Object : in out Object_Ref) is
begin
if Object.Object /= null then
Util.Concurrent.Counters.Increment (Object.Object.Counter);
end if;
end Adjust;
procedure Finalize (Object : in out Object_Ref) is
Is_Zero : Boolean;
begin
if Object.Object /= null then
Util.Concurrent.Counters.Decrement (Object.Object.Counter, Is_Zero);
if Is_Zero then
Destroy (Object.Object);
Object.Object := null;
end if;
end if;
end Finalize;
-- ------------------------------
-- Mark the field identified by <b>Field</b> as modified.
-- ------------------------------
procedure Set_Field (Object : in out Object_Ref'Class;
Field : in Positive) is
begin
if Object.Object = null then
Object.Allocate;
end if;
Object.Object.Modified (Field) := True;
end Set_Field;
-- ------------------------------
-- Check whether this object is initialized or not.
-- ------------------------------
function Is_Null (Object : in Object_Ref'Class) return Boolean is
begin
return Object.Object = null;
end Is_Null;
-- ------------------------------
-- Internal method to get the object record instance.
-- ------------------------------
function Get_Object (Ref : in Object_Ref'Class) return Object_Record_Access is
begin
return Ref.Object;
end Get_Object;
-- ------------------------------
-- Check if the two objects are the same database objects.
-- The comparison is only made on the primary key.
-- Returns true if the two objects have the same primary key.
-- ------------------------------
function "=" (Left : Object_Ref'Class; Right : Object_Ref'Class) return Boolean is
begin
-- Same target object
if Left.Object = Right.Object then
return True;
end if;
-- One of the target object is null
if Left.Object = null or Right.Object = null then
return False;
end if;
return Left.Object.Key = Right.Object.Key;
end "=";
procedure Set_Object (Ref : in out Object_Ref'Class;
Object : in Object_Record_Access) is
Is_Zero : Boolean;
begin
if Ref.Object /= null and Ref.Object /= Object then
Util.Concurrent.Counters.Decrement (Ref.Object.Counter, Is_Zero);
if Is_Zero then
Destroy (Ref.Object);
end if;
end if;
Ref.Object := Object;
end Set_Object;
-- ------------------------------
-- Get the object key
-- ------------------------------
function Get_Id (Ref : in Object_Record'Class) return Object_Key is
begin
return Ref.Key;
end Get_Id;
-- ------------------------------
-- Check if this is a new object.
-- Returns True if an insert is necessary to persist this object.
-- ------------------------------
function Is_Created (Ref : in Object_Record'Class) return Boolean is
begin
return Ref.Is_Created;
end Is_Created;
-- ------------------------------
-- Mark the object as created in the database.
-- ------------------------------
procedure Set_Created (Ref : in out Object_Record'Class) is
begin
Ref.Is_Created := True;
end Set_Created;
-- ------------------------------
-- Check if the field at position <b>Field</b> was modified.
-- ------------------------------
function Is_Modified (Ref : in Object_Record'Class;
Field : in Positive) return Boolean is
begin
return Ref.Modified (Field);
end Is_Modified;
-- ------------------------------
-- Clear the modification flag associated with the field at
-- position <b>Field</b>.
-- ------------------------------
procedure Clear_Modified (Ref : in out Object_Record'Class;
Field : in Positive) is
begin
Ref.Modified (Field) := False;
end Clear_Modified;
end ADO.Objects;
|
Add comment
|
Add comment
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
30947499e1602ea74b0d43c4da96cd13bdd8ccac
|
regtests/gen-artifacts-xmi-tests.adb
|
regtests/gen-artifacts-xmi-tests.adb
|
-----------------------------------------------------------------------
-- gen-xmi-tests -- Tests for xmi
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Generator;
package body Gen.Artifacts.XMI.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.XMI");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration",
Test_Read_XMI'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Element'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the XMI files defines in the Dynamo UML configuration repository.
-- ------------------------------
procedure Test_Read_XMI (T : in out Test) is
procedure Check (Namespace : in String;
Name : in String;
Id : in String);
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use type Gen.Model.XMI.Model_Element_Access;
procedure Check (Namespace : in String;
Name : in String;
Id : in String) is
Empty : Gen.Model.XMI.Model_Map.Map;
XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id);
N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes,
Empty,
XMI_Id);
begin
T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id));
Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name");
end Check;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
-- ArgoUML Integer DataType
Check ("default-uml14.xmi", "Integer",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C");
-- ArgoUML String DataType
Check ("default-uml14.xmi", "String",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E");
-- ArgoUML documentation TagDefinition
Check ("default-uml14.xmi", "documentation",
".:000000000000087C");
-- ArgoUML type Stereotype
Check ("default-uml14.xmi", "type",
".:0000000000000842");
-- Persistence Table Stereotype
Check ("Dynamo.xmi", "Table",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F");
Check ("Dynamo.xmi", "PK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50");
Check ("Dynamo.xmi", "FK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70");
Check ("Dynamo.xmi", "Bean",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72");
end Test_Read_XMI;
-- ------------------------------
-- Test searching an XMI element by using a qualified name.
-- ------------------------------
procedure Test_Find_Element (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Stereotype is
new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element,
Element_Type_Access => Stereotype_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
S : Gen.Model.XMI.Stereotype_Element_Access;
begin
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
end;
end Test_Find_Element;
end Gen.Artifacts.XMI.Tests;
|
-----------------------------------------------------------------------
-- gen-xmi-tests -- Tests for xmi
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Generator;
package body Gen.Artifacts.XMI.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.XMI");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration",
Test_Read_XMI'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Element'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the XMI files defines in the Dynamo UML configuration repository.
-- ------------------------------
procedure Test_Read_XMI (T : in out Test) is
procedure Check (Namespace : in String;
Name : in String;
Id : in String);
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use type Gen.Model.XMI.Model_Element_Access;
procedure Check (Namespace : in String;
Name : in String;
Id : in String) is
Empty : Gen.Model.XMI.Model_Map.Map;
XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id);
N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes,
Empty,
XMI_Id);
begin
T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id));
Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name");
end Check;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
-- ArgoUML Integer DataType
Check ("default-uml14.xmi", "Integer",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C");
-- ArgoUML String DataType
Check ("default-uml14.xmi", "String",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E");
-- ArgoUML documentation TagDefinition
Check ("default-uml14.xmi", "documentation",
".:000000000000087C");
-- ArgoUML type Stereotype
Check ("default-uml14.xmi", "type",
".:0000000000000842");
-- Persistence Table Stereotype
Check ("Dynamo.xmi", "Table",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F");
Check ("Dynamo.xmi", "PK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50");
Check ("Dynamo.xmi", "FK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70");
Check ("Dynamo.xmi", "Bean",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72");
end Test_Read_XMI;
-- ------------------------------
-- Test searching an XMI element by using a qualified name.
-- ------------------------------
procedure Test_Find_Element (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Stereotype is
new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element,
Element_Type_Access => Stereotype_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
S : Gen.Model.XMI.Stereotype_Element_Access;
begin
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
end;
end Test_Find_Element;
end Gen.Artifacts.XMI.Tests;
|
Check new stereotypes necessary for the code gneration
|
Check new stereotypes necessary for the code gneration
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
685f34b1bd546570ef7358560f8060ebc1becfe7
|
regtests/gen-artifacts-xmi-tests.adb
|
regtests/gen-artifacts-xmi-tests.adb
|
-----------------------------------------------------------------------
-- gen-xmi-tests -- Tests for xmi
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Generator;
package body Gen.Artifacts.XMI.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.XMI");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration",
Test_Read_XMI'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Element'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the XMI files defines in the Dynamo UML configuration repository.
-- ------------------------------
procedure Test_Read_XMI (T : in out Test) is
procedure Check (Namespace : in String;
Name : in String;
Id : in String);
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use type Gen.Model.XMI.Model_Element_Access;
procedure Check (Namespace : in String;
Name : in String;
Id : in String) is
Empty : Gen.Model.XMI.Model_Map.Map;
XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id);
N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes,
Empty,
XMI_Id);
begin
T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id));
Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name");
end Check;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
-- ArgoUML Integer DataType
Check ("default-uml14.xmi", "Integer",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C");
-- ArgoUML String DataType
Check ("default-uml14.xmi", "String",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E");
-- ArgoUML documentation TagDefinition
Check ("default-uml14.xmi", "documentation",
".:000000000000087C");
-- ArgoUML type Stereotype
Check ("default-uml14.xmi", "type",
".:0000000000000842");
-- Persistence Table Stereotype
Check ("Dynamo.xmi", "Table",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F");
Check ("Dynamo.xmi", "PK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50");
Check ("Dynamo.xmi", "FK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70");
Check ("Dynamo.xmi", "Bean",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72");
end Test_Read_XMI;
-- ------------------------------
-- Test searching an XMI element by using a qualified name.
-- ------------------------------
procedure Test_Find_Element (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Stereotype is
new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element,
Element_Type_Access => Stereotype_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
S : Gen.Model.XMI.Stereotype_Element_Access;
begin
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
end;
end Test_Find_Element;
end Gen.Artifacts.XMI.Tests;
|
-----------------------------------------------------------------------
-- gen-xmi-tests -- Tests for xmi
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Gen.Generator;
package body Gen.Artifacts.XMI.Tests is
use Ada.Strings.Unbounded;
package Caller is new Util.Test_Caller (Test, "Gen.XMI");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration",
Test_Read_XMI'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Element'Access);
Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element",
Test_Find_Tag_Definition'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the XMI files defines in the Dynamo UML configuration repository.
-- ------------------------------
procedure Test_Read_XMI (T : in out Test) is
procedure Check (Namespace : in String;
Name : in String;
Id : in String);
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use type Gen.Model.XMI.Model_Element_Access;
procedure Check (Namespace : in String;
Name : in String;
Id : in String) is
Empty : Gen.Model.XMI.Model_Map.Map;
XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id);
N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes,
Empty,
XMI_Id);
begin
T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id));
Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name");
end Check;
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
-- ArgoUML Integer DataType
Check ("default-uml14.xmi", "Integer",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C");
-- ArgoUML String DataType
Check ("default-uml14.xmi", "String",
"-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E");
-- ArgoUML documentation TagDefinition
Check ("default-uml14.xmi", "documentation",
".:000000000000087C");
-- ArgoUML type Stereotype
Check ("default-uml14.xmi", "type",
".:0000000000000842");
-- Persistence Table Stereotype
Check ("Dynamo.xmi", "Table",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F");
Check ("Dynamo.xmi", "PK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50");
Check ("Dynamo.xmi", "FK",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70");
Check ("Dynamo.xmi", "Bean",
"127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72");
end Test_Read_XMI;
-- ------------------------------
-- Test searching an XMI element by using a qualified name.
-- ------------------------------
procedure Test_Find_Element (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Stereotype is
new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element,
Element_Type_Access => Stereotype_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
S : Gen.Model.XMI.Stereotype_Element_Access;
begin
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME);
T.Assert (S /= null, "Stereotype not found");
end;
end Test_Find_Element;
-- Test searching an XMI Tag definition element by using its name.
procedure Test_Find_Tag_Definition (T : in out Test) is
A : Artifact;
G : Gen.Generator.Handler;
C : constant String := Util.Tests.Get_Parameter ("config_dir", "config");
use Gen.Model.XMI;
function Find_Tag_Definition is
new Gen.Model.XMI.Find_Element (Element_Type => Tag_Definition_Element,
Element_Type_Access => Tag_Definition_Element_Access);
begin
Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False);
A.Read_UML_Configuration (G);
declare
Tag : Tag_Definition_Element_Access;
begin
Tag := Find_Tag_Definition (A.Nodes, "Dynamo.xmi", "[email protected]",
Gen.Model.XMI.BY_NAME);
T.Assert (Tag /= null, "Tag definition not found");
end;
end Test_Find_Tag_Definition;
end Gen.Artifacts.XMI.Tests;
|
Implement the new unit test for tag definition
|
Implement the new unit test for tag definition
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
d737efedfa576fa39ba5d7fc7f69e820ea1448a2
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Returns true if the given permission is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Test_Principal;
Role : in Security.Policies.Roles.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
M.Add_Policy (R.all'Access);
M.Read_Policy (Util.Files.Compose (Path, "empty.xml"));
R.Add_Role_Type (Name => "admin",
Result => Admin_Perm);
R.Add_Role_Type (Name => "manager",
Result => Manager_Perm);
M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml"));
User.Roles (Admin_Perm) := True;
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
-- end;
--
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/list.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
-- end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (1);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, File));
--
-- Admin_Perm := M.Find_Role (Role);
--
-- Context.Set_Context (Manager => M'Unchecked_Access,
-- Principal => User'Unchecked_Access);
--
-- declare
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- -- A user without the role should not have the permission.
-- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was granted for user without role. URI=" & URI);
--
-- -- Set the role.
-- User.Roles (Admin_Perm) := True;
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was not granted for user with role. URI=" & URI);
-- end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Returns true if the given permission is stored in the user principal.
-- ------------------------------
function Has_Role (User : in Test_Principal;
Role : in Security.Policies.Roles.Role_Type) return Boolean is
begin
return User.Roles (Role);
end Has_Role;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
M.Add_Policy (R.all'Access);
M.Read_Policy (Util.Files.Compose (Path, "empty.xml"));
R.Add_Role_Type (Name => "admin",
Result => Admin_Perm);
R.Add_Role_Type (Name => "manager",
Result => Manager_Perm);
M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml"));
User.Roles (Admin_Perm) := True;
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)");
-- end;
--
-- declare
-- S : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1_000 loop
-- declare
-- URI : constant String := "/admin/home/list.html";
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P), "Permission not granted");
-- end;
-- end loop;
-- Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
-- end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (1);
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
User : aliased Test_Principal;
Admin_Perm : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
begin
M.Read_Policy (Util.Files.Compose (Path, File));
--
-- Admin_Perm := M.Find_Role (Role);
--
-- Context.Set_Context (Manager => M'Unchecked_Access,
-- Principal => User'Unchecked_Access);
--
-- declare
-- P : constant URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
-- begin
-- -- A user without the role should not have the permission.
-- T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was granted for user without role. URI=" & URI);
--
-- -- Set the role.
-- User.Roles (Admin_Perm) := True;
-- T.Assert (M.Has_Permission (Context => Context'Unchecked_Access,
-- Permission => P),
-- "Permission was not granted for user with role. URI=" & URI);
-- end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
f855b95f726d0e418100dd9c75224628ce0a232f
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
private with Wiki.Buffers;
private with Util.Stacks;
private with Wiki.Nodes;
private with Wiki.Html_Parser;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
subtype Parser_Type is Parser;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Trim_End is (None, Left, Right, Both);
use Wiki.Strings.Wide_Wide_Builders;
type Block_Type is record
Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH;
Level : Natural := 0;
Marker : Wiki.Strings.WChar := ' ';
Number : Integer := 0;
end record;
type Parser_State_Type is (State_Html_Doctype,
State_Html_Comment,
State_Html_Attribute,
State_Html_Element);
type Block_Access is access all Block_Type;
package Block_Stack is new Util.Stacks (Element_Type => Block_Type,
Element_Type_Access => Block_Access);
type Parser_Handler is access procedure (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access);
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Previous_Syntax : Wiki_Syntax;
Document : Wiki.Documents.Document;
Parse_Block : Parser_Handler;
Parse_Inline : Parser_Handler;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Line_Buffer : Wiki.Buffers.Builder (512);
Text_Buffer : Wiki.Buffers.Builder (512);
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_Table : Boolean := False;
In_Html : Boolean := False;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE;
Blocks : Block_Stack.Stack;
Previous_Line_Empty : Boolean := False;
Header_Level : Natural := 0;
Is_Empty_Paragraph : Boolean := True;
Pre_Tag_Counter : Natural := 0;
-- Pre-format code block
Preformat_Fence : Wiki.Strings.WChar;
Preformat_Indent : Natural := 0;
Preformat_Fcount : Natural := 0;
Preformat_Format : Wiki.Strings.BString (32);
Html : Wiki.Html_Parser.Parser_Type;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (Parser : in out Parser_Type'Class;
Buffer : out Wiki.Buffers.Buffer_Access);
function Is_List_Item (P : in Parser;
Level : in Natural) return Boolean;
function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access;
From : in Positive;
Token : in Wiki.Strings.WChar) return Boolean;
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser;
Trim : in Trim_End := None);
procedure Flush_Block (Parser : in out Parser_Type);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Pop_List (P : in out Parser;
Level : in Natural;
Marker : in Wiki.Strings.WChar;
Number : in Natural);
procedure Pop_List (P : in out Parser);
function Get_Current_Level (Parser : in Parser_Type) return Natural;
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Process_Html (P : in out Parser;
Kind : in Wiki.Html_Parser.State_Type;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a single character sequence.
-- Example:
-- _name_ *bold* `code`
procedure Parse_Format (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence.
-- Example:
-- --name-- **bold** ~~strike~~
procedure Parse_Format_Double (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Push a new block kind on the block stack.
procedure Push_Block (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer := 0;
Marker : in Wiki.Strings.WChar := ' ';
Number : in Integer := 0);
-- Pop the current block stack.
procedure Pop_Block (P : in out Parser);
procedure Pop_All (P : in out Parser);
procedure Pop_Block_Until (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer);
procedure Append_Text (P : in out Parser;
Text : in Wiki.Strings.BString;
From : in Positive;
To : in Positive);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
private with Wiki.Buffers;
private with Util.Stacks;
private with Wiki.Nodes;
private with Wiki.Html_Parser;
-- == Wiki Parsers {#wiki-parsers} ==
-- The `Wikis.Parsers` package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki `Document`
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- `Set_Syntax` procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- `Add_Filter` procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki `Document` is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The `Parse` procedure is then used to parse either a string content or some stream
-- represented by the `Input_Stream` interface. After the `Parse` procedure
-- completes, the `Document` instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
subtype Parser_Type is Parser;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Trim_End is (None, Left, Right, Both);
use Wiki.Strings.Wide_Wide_Builders;
type Block_Type is record
Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH;
Level : Natural := 0;
Marker : Wiki.Strings.WChar := ' ';
Number : Integer := 0;
Quote_Level : Natural := 0;
end record;
type Parser_State_Type is (State_Html_Doctype,
State_Html_Comment,
State_Html_Attribute,
State_Html_Element);
type Block_Access is access all Block_Type;
package Block_Stack is new Util.Stacks (Element_Type => Block_Type,
Element_Type_Access => Block_Access);
type Parser_Handler is access procedure (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access);
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Previous_Syntax : Wiki_Syntax;
Document : Wiki.Documents.Document;
Parse_Block : Parser_Handler;
Parse_Inline : Parser_Handler;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Line_Buffer : Wiki.Buffers.Builder (512);
Text_Buffer : Wiki.Buffers.Builder (512);
Empty_Line : Boolean := True;
Is_Last_Line : Boolean := False;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_Table : Boolean := False;
In_Html : Boolean := False;
In_Blockquote : Boolean := False;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Previous_Tag : Html_Tag := UNKNOWN_TAG;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE;
Blocks : Block_Stack.Stack;
Previous_Line_Empty : Boolean := False;
Header_Level : Natural := 0;
Is_Empty_Paragraph : Boolean := True;
Pre_Tag_Counter : Natural := 0;
-- Pre-format code block
Preformat_Fence : Wiki.Strings.WChar;
Preformat_Indent : Natural := 0;
Preformat_Fcount : Natural := 0;
Preformat_Format : Wiki.Strings.BString (32);
Html : Wiki.Html_Parser.Parser_Type;
end record;
-- Read the next wiki input line in the line buffer.
procedure Read_Line (Parser : in out Parser_Type'Class;
Buffer : out Wiki.Buffers.Buffer_Access);
function Is_List_Item (P : in Parser;
Level : in Natural) return Boolean;
function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access;
From : in Positive;
Token : in Wiki.Strings.WChar) return Boolean;
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser;
Trim : in Trim_End := None);
procedure Flush_Block (Parser : in out Parser_Type);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
procedure Pop_List (P : in out Parser;
Level : in Natural;
Marker : in Wiki.Strings.WChar;
Number : in Natural);
procedure Pop_List (P : in out Parser);
function Get_Current_Level (Parser : in Parser_Type) return Natural;
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Returns true if we are included from another wiki content.
function Is_Included (P : in Parser) return Boolean;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
procedure Process_Html (P : in out Parser;
Kind : in Wiki.Html_Parser.State_Type;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Toggle_Format (P : in out Parser;
Format : in Format_Type);
-- Parse the beginning or the end of a single character sequence.
-- Example:
-- _name_ *bold* `code`
procedure Parse_Format (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Parse the beginning or the end of a double character sequence.
-- Example:
-- --name-- **bold** ~~strike~~
procedure Parse_Format_Double (P : in out Parser;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive;
Expect : in Wiki.Strings.WChar;
Format : in Format_Type);
-- Push a new block kind on the block stack.
procedure Push_Block (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer := 0;
Marker : in Wiki.Strings.WChar := ' ';
Number : in Integer := 0);
-- Pop the current block stack.
procedure Pop_Block (P : in out Parser);
procedure Pop_All (P : in out Parser);
procedure Pop_Block_Until (P : in out Parser;
Kind : in Wiki.Nodes.Node_Kind;
Level : in Integer);
procedure Append_Text (P : in out Parser;
Text : in Wiki.Strings.BString;
From : in Positive;
To : in Positive);
NAME_ATTR : aliased constant String := "name";
HREF_ATTR : aliased constant String := "href";
LANG_ATTR : aliased constant String := "lang";
TITLE_ATTR : aliased constant String := "title";
end Wiki.Parsers;
|
Add Quote_Level in the stack block
|
Add Quote_Level in the stack block
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
80907c146888c7146525a63f4f9c88c8f15b5507
|
src/wiki-streams.ads
|
src/wiki-streams.ads
|
-----------------------------------------------------------------------
-- wiki-streams -- Wiki input and output streams
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
-- == Input and Output streams ==
-- The <tt>Wiki.Streams</tt> package defines the interfaces used by
-- the parser or renderer to read and write their outputs.
--
-- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to
-- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser
-- repeatedly while scanning the Wiki content.
--
-- The <tt>Output_Stream</tt> interface is the interface used by the renderer
-- to write their outpus. It defines the <tt>Write</tt> procedure to write
-- a single character or a string.
--
-- @include wiki-streams-html.ads
-- @include wiki-streams-builders.ads
-- @include wiki-streams-html-builders.ads
package Wiki.Streams is
pragma Preelaborate;
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
procedure Read (Input : in out Input_Stream;
Char : out Wiki.Strings.WChar;
Eof : out Boolean) is abstract;
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the string to the output stream.
procedure Write (Stream : in out Output_Stream;
Content : in Wiki.Strings.WString) is abstract;
-- Write a single character to the output stream.
procedure Write (Stream : in out Output_Stream;
Char : in Wiki.Strings.WChar) is abstract;
end Wiki.Streams;
|
-----------------------------------------------------------------------
-- wiki-streams -- Wiki input and output streams
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
-- == Input and Output streams ==
-- The <tt>Wiki.Streams</tt> package defines the interfaces used by
-- the parser or renderer to read and write their outputs.
--
-- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to
-- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser
-- repeatedly while scanning the Wiki content.
--
-- The <tt>Output_Stream</tt> interface is the interface used by the renderer
-- to write their outpus. It defines the <tt>Write</tt> procedure to write
-- a single character or a string.
--
-- @include wiki-streams-html.ads
-- @include wiki-streams-builders.ads
-- @include wiki-streams-html-builders.ads
-- @include wiki-streams-text_io.ads
-- @include wiki-streams-html-text_io.ads
package Wiki.Streams is
pragma Preelaborate;
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
procedure Read (Input : in out Input_Stream;
Char : out Wiki.Strings.WChar;
Eof : out Boolean) is abstract;
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the string to the output stream.
procedure Write (Stream : in out Output_Stream;
Content : in Wiki.Strings.WString) is abstract;
-- Write a single character to the output stream.
procedure Write (Stream : in out Output_Stream;
Char : in Wiki.Strings.WChar) is abstract;
end Wiki.Streams;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
0a0b9ae56bf98ab38dfebc3c448f0e7fe19a947a
|
src/ado-sessions.ads
|
src/ado-sessions.ads
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Databases;
with ADO.Queries;
with ADO.SQL;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status;
-- Close the session.
procedure Close (Database : in out Session);
-- Get the database connection.
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class;
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
type Session_Proxy is limited private;
type Session_Proxy_Access is access all Session_Proxy;
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access constant ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
type Session_Proxy is limited record
Counter : Util.Concurrent.Counters.Counter;
Session : Session_Record_Access;
Factory : Object_Factory_Access;
end record;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Natural := 1;
Database : ADO.Databases.Master_Connection;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class);
pragma Inline (Check_Session);
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Databases;
with ADO.Queries;
with ADO.SQL;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return ADO.Databases.Connection_Status;
-- Close the session.
procedure Close (Database : in out Session);
-- Get the database connection.
function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class;
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
type Session_Proxy is limited private;
type Session_Proxy_Access is access all Session_Proxy;
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access constant ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
type Session_Proxy is limited record
Counter : Util.Concurrent.Counters.Counter;
Session : Session_Record_Access;
Factory : Object_Factory_Access;
end record;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Natural := 1;
Database : ADO.Databases.Master_Connection;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class);
pragma Inline (Check_Session);
end ADO.Sessions;
|
Change the Factory_Access to add 'all' access types
|
Change the Factory_Access to add 'all' access types
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
7f0cf5486b3c526ba66d6e05ff827d9a26cfd7f8
|
mat/src/gtk/mat-targets-gtkmat.ads
|
mat/src/gtk/mat-targets-gtkmat.ads
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Gtk.Widget;
with Gtkada.Builder;
with MAT.Events.Gtkmat;
with MAT.Consoles.Gtkmat;
package MAT.Targets.Gtkmat is
type Target_Type is new MAT.Targets.Target_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target instance.
overriding
procedure Initialize (Target : in out Target_Type);
-- Release the storage.
overriding
procedure Finalize (Target : in out Target_Type);
-- Initialize the widgets and create the Gtk gui.
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
overriding
procedure Interactive (Target : in out Target_Type);
-- Set the UI label with the given value.
procedure Set_Label (Target : in Target_Type;
Name : in String;
Value : in String);
-- Refresh the information about the current process.
procedure Refresh_Process (Target : in out Target_Type);
private
task type Gtk_Loop is
entry Start (Target : in Target_Type_Access);
end Gtk_Loop;
type Target_Type is new MAT.Targets.Target_Type with record
Builder : Gtkada.Builder.Gtkada_Builder;
Gui_Task : Gtk_Loop;
Previous_Event_Counter : Integer := 0;
Gtk_Console : MAT.Consoles.Gtkmat.Console_Type_Access;
Main : Gtk.Widget.Gtk_Widget;
About : Gtk.Widget.Gtk_Widget;
Chooser : Gtk.Widget.Gtk_Widget;
Events : MAT.Events.Gtkmat.Event_Drawing_Type;
end record;
procedure Refresh_Events (Target : in out Target_Type);
end MAT.Targets.Gtkmat;
|
-----------------------------------------------------------------------
-- mat-targets-gtkmat - Gtk target management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Gtk.Widget;
with Gtkada.Builder;
with MAT.Events.Gtkmat;
with MAT.Consoles.Gtkmat;
package MAT.Targets.Gtkmat is
type Target_Type is new MAT.Targets.Target_Type with private;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target instance.
overriding
procedure Initialize (Target : in out Target_Type);
-- Release the storage.
overriding
procedure Finalize (Target : in out Target_Type);
-- Initialize the widgets and create the Gtk gui.
procedure Initialize_Widget (Target : in out Target_Type;
Widget : out Gtk.Widget.Gtk_Widget);
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
overriding
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
overriding
procedure Interactive (Target : in out Target_Type);
-- Set the UI label with the given value.
procedure Set_Label (Target : in Target_Type;
Name : in String;
Value : in String);
-- Refresh the information about the current process.
procedure Refresh_Process (Target : in out Target_Type);
private
-- Load the glade XML definition.
procedure Load_UI (Target : in out Target_Type);
task type Gtk_Loop is
entry Start (Target : in Target_Type_Access);
end Gtk_Loop;
type Target_Type is new MAT.Targets.Target_Type with record
Builder : Gtkada.Builder.Gtkada_Builder;
Gui_Task : Gtk_Loop;
Previous_Event_Counter : Integer := 0;
Gtk_Console : MAT.Consoles.Gtkmat.Console_Type_Access;
Main : Gtk.Widget.Gtk_Widget;
About : Gtk.Widget.Gtk_Widget;
Chooser : Gtk.Widget.Gtk_Widget;
Events : MAT.Events.Gtkmat.Event_Drawing_Type;
end record;
procedure Refresh_Events (Target : in out Target_Type);
end MAT.Targets.Gtkmat;
|
Declare the Load_UI procedure
|
Declare the Load_UI procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
4ed44b76af63c8f9c8d7bbb2d2afeeec89cdebae
|
src/asf-utils.adb
|
src/asf-utils.adb
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ASF.Utils is
TITLE_ATTR : aliased constant String := "title";
STYLE_ATTR : aliased constant String := "style";
STYLE_CLASS_ATTR : aliased constant String := "styleClass";
DIR_ATTR : aliased constant String := "dir";
LANG_ATTR : aliased constant String := "lang";
ACCESS_KEY_ATTR : aliased constant String := "accesskey";
ON_BLUR_ATTR : aliased constant String := "onblur";
ON_CLICK_ATTR : aliased constant String := "onclick";
ON_DBLCLICK_ATTR : aliased constant String := "ondblclick";
ON_FOCUS_ATTR : aliased constant String := "onfocus";
ON_KEYDOWN_ATTR : aliased constant String := "onkeydown";
ON_KEYUP_ATTR : aliased constant String := "onkeyup";
ON_MOUSE_DOWN_ATTR : aliased constant String := "onmousedown";
ON_MOUSE_MOVE_ATTR : aliased constant String := "onmousemove";
ON_MOUSE_OUT_ATTR : aliased constant String := "onmouseout";
ON_MOUSE_OVER_ATTR : aliased constant String := "onmouseover";
ON_MOUSE_UP_ATTR : aliased constant String := "onmouseup";
ON_RESET_ATTR : aliased constant String := "onreset";
ON_SUBMIT_ATTR : aliased constant String := "onsubmit";
ENCTYPE_ATTR : aliased constant String := "enctype";
ON_LOAD_ATTR : aliased constant String := "onload";
ON_UNLOAD_ATTR : aliased constant String := "onunload";
TABINDEX_ATTR : aliased constant String := "tabindex";
AUTOCOMPLETE_ATTR : aliased constant String := "autocomplete";
SIZE_ATTR : aliased constant String := "size";
MAXLENGTH_ATTR : aliased constant String := "maxlength";
ALT_ATTR : aliased constant String := "alt";
DISABLED_ATTR : aliased constant String := "disabled";
READONLY_ATTR : aliased constant String := "readonly";
ACCEPT_ATTR : aliased constant String := "accept";
ROWS_ATTR : aliased constant String := "rows";
COLS_ATTR : aliased constant String := "cols";
CHARSET_ATTR : aliased constant String := "charset";
SHAPE_ATTR : aliased constant String := "shape";
REV_ATTR : aliased constant String := "rev";
COORDS_ATTR : aliased constant String := "coords";
TARGET_ATTR : aliased constant String := "target";
HREFLANG_ATTR : aliased constant String := "hreflang";
-- ------------------------------
-- Add in the <b>names</b> set, the basic text attributes that can be set
-- on HTML elements (dir, lang, style, title).
-- ------------------------------
procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (STYLE_CLASS_ATTR'Access);
Names.Insert (TITLE_ATTR'Access);
Names.Insert (DIR_ATTR'Access);
Names.Insert (LANG_ATTR'Access);
Names.Insert (STYLE_ATTR'Access);
end Set_Text_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the onXXX attributes that can be set
-- on HTML elements (accesskey, tabindex, onXXX).
-- ------------------------------
procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ACCESS_KEY_ATTR'Access);
Names.Insert (TABINDEX_ATTR'Access);
Names.Insert (ON_BLUR_ATTR'Access);
Names.Insert (ON_MOUSE_UP_ATTR'Access);
Names.Insert (ON_MOUSE_OVER_ATTR'Access);
Names.Insert (ON_MOUSE_OUT_ATTR'Access);
Names.Insert (ON_MOUSE_MOVE_ATTR'Access);
Names.Insert (ON_MOUSE_DOWN_ATTR'Access);
Names.Insert (ON_KEYUP_ATTR'Access);
Names.Insert (ON_KEYDOWN_ATTR'Access);
Names.Insert (ON_FOCUS_ATTR'Access);
Names.Insert (ON_DBLCLICK_ATTR'Access);
Names.Insert (ON_CLICK_ATTR'Access);
end Set_Interactive_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the size attributes that can be set
-- on HTML elements.
-- ------------------------------
procedure Set_Input_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (SIZE_ATTR'Access);
Names.Insert (AUTOCOMPLETE_ATTR'Access);
Names.Insert (MAXLENGTH_ATTR'Access);
Names.Insert (ALT_ATTR'Access);
Names.Insert (DISABLED_ATTR'Access);
Names.Insert (READONLY_ATTR'Access);
end Set_Input_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the size attributes that can be set
-- on <textarea> elements.
-- ------------------------------
procedure Set_Textarea_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ROWS_ATTR'Access);
Names.Insert (COLS_ATTR'Access);
end Set_Textarea_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the online and onunload attributes that can be set
-- on <body> elements.
-- ------------------------------
procedure Set_Body_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ON_LOAD_ATTR'Access);
Names.Insert (ON_UNLOAD_ATTR'Access);
end Set_Body_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the dir, lang attributes that can be set
-- on <head> elements.
-- ------------------------------
procedure Set_Head_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (DIR_ATTR'Access);
Names.Insert (LANG_ATTR'Access);
end Set_Head_Attributes;
--------------------
-- Add in the <b>names</b> set, the onreset and onsubmit attributes that can be set
-- on <form> elements.
-- ------------------------------
procedure Set_Form_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ON_RESET_ATTR'Access);
Names.Insert (ON_SUBMIT_ATTR'Access);
Names.Insert (ENCTYPE_ATTR'Access);
end Set_Form_Attributes;
--------------------
-- Add in the <b>names</b> set, the attributes which are specific to a link.
-- ------------------------------
procedure Set_Link_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (CHARSET_ATTR'Access);
Names.Insert (SHAPE_ATTR'Access);
Names.Insert (REV_ATTR'Access);
Names.Insert (COORDS_ATTR'Access);
Names.Insert (TARGET_ATTR'Access);
Names.Insert (HREFLANG_ATTR'Access);
end Set_Link_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the attributes which are specific to an input file.
-- ------------------------------
procedure Set_File_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ACCEPT_ATTR'Access);
end Set_File_Attributes;
end ASF.Utils;
|
-----------------------------------------------------------------------
-- html -- ASF HTML Components
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ASF.Utils is
TITLE_ATTR : aliased constant String := "title";
STYLE_ATTR : aliased constant String := "style";
STYLE_CLASS_ATTR : aliased constant String := "styleClass";
DIR_ATTR : aliased constant String := "dir";
LANG_ATTR : aliased constant String := "lang";
ACCESS_KEY_ATTR : aliased constant String := "accesskey";
ON_BLUR_ATTR : aliased constant String := "onblur";
ON_CLICK_ATTR : aliased constant String := "onclick";
ON_DBLCLICK_ATTR : aliased constant String := "ondblclick";
ON_FOCUS_ATTR : aliased constant String := "onfocus";
ON_KEYDOWN_ATTR : aliased constant String := "onkeydown";
ON_KEYUP_ATTR : aliased constant String := "onkeyup";
ON_MOUSE_DOWN_ATTR : aliased constant String := "onmousedown";
ON_MOUSE_MOVE_ATTR : aliased constant String := "onmousemove";
ON_MOUSE_OUT_ATTR : aliased constant String := "onmouseout";
ON_MOUSE_OVER_ATTR : aliased constant String := "onmouseover";
ON_MOUSE_UP_ATTR : aliased constant String := "onmouseup";
ON_CHANGE_ATTR : aliased constant String := "onchange";
ON_RESET_ATTR : aliased constant String := "onreset";
ON_SUBMIT_ATTR : aliased constant String := "onsubmit";
ENCTYPE_ATTR : aliased constant String := "enctype";
ON_LOAD_ATTR : aliased constant String := "onload";
ON_UNLOAD_ATTR : aliased constant String := "onunload";
TABINDEX_ATTR : aliased constant String := "tabindex";
AUTOCOMPLETE_ATTR : aliased constant String := "autocomplete";
SIZE_ATTR : aliased constant String := "size";
MAXLENGTH_ATTR : aliased constant String := "maxlength";
ALT_ATTR : aliased constant String := "alt";
DISABLED_ATTR : aliased constant String := "disabled";
READONLY_ATTR : aliased constant String := "readonly";
ACCEPT_ATTR : aliased constant String := "accept";
ROWS_ATTR : aliased constant String := "rows";
COLS_ATTR : aliased constant String := "cols";
CHARSET_ATTR : aliased constant String := "charset";
SHAPE_ATTR : aliased constant String := "shape";
REV_ATTR : aliased constant String := "rev";
COORDS_ATTR : aliased constant String := "coords";
TARGET_ATTR : aliased constant String := "target";
HREFLANG_ATTR : aliased constant String := "hreflang";
-- ------------------------------
-- Add in the <b>names</b> set, the basic text attributes that can be set
-- on HTML elements (dir, lang, style, title).
-- ------------------------------
procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (STYLE_CLASS_ATTR'Access);
Names.Insert (TITLE_ATTR'Access);
Names.Insert (DIR_ATTR'Access);
Names.Insert (LANG_ATTR'Access);
Names.Insert (STYLE_ATTR'Access);
end Set_Text_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the onXXX attributes that can be set
-- on HTML elements (accesskey, tabindex, onXXX).
-- ------------------------------
procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ACCESS_KEY_ATTR'Access);
Names.Insert (TABINDEX_ATTR'Access);
Names.Insert (ON_BLUR_ATTR'Access);
Names.Insert (ON_MOUSE_UP_ATTR'Access);
Names.Insert (ON_MOUSE_OVER_ATTR'Access);
Names.Insert (ON_MOUSE_OUT_ATTR'Access);
Names.Insert (ON_MOUSE_MOVE_ATTR'Access);
Names.Insert (ON_MOUSE_DOWN_ATTR'Access);
Names.Insert (ON_KEYUP_ATTR'Access);
Names.Insert (ON_KEYDOWN_ATTR'Access);
Names.Insert (ON_FOCUS_ATTR'Access);
Names.Insert (ON_DBLCLICK_ATTR'Access);
Names.Insert (ON_CLICK_ATTR'Access);
Names.Insert (ON_CHANGE_ATTR'Access);
end Set_Interactive_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the size attributes that can be set
-- on HTML elements.
-- ------------------------------
procedure Set_Input_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (SIZE_ATTR'Access);
Names.Insert (AUTOCOMPLETE_ATTR'Access);
Names.Insert (MAXLENGTH_ATTR'Access);
Names.Insert (ALT_ATTR'Access);
Names.Insert (DISABLED_ATTR'Access);
Names.Insert (READONLY_ATTR'Access);
end Set_Input_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the size attributes that can be set
-- on <textarea> elements.
-- ------------------------------
procedure Set_Textarea_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ROWS_ATTR'Access);
Names.Insert (COLS_ATTR'Access);
end Set_Textarea_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the online and onunload attributes that can be set
-- on <body> elements.
-- ------------------------------
procedure Set_Body_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ON_LOAD_ATTR'Access);
Names.Insert (ON_UNLOAD_ATTR'Access);
end Set_Body_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the dir, lang attributes that can be set
-- on <head> elements.
-- ------------------------------
procedure Set_Head_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (DIR_ATTR'Access);
Names.Insert (LANG_ATTR'Access);
end Set_Head_Attributes;
--------------------
-- Add in the <b>names</b> set, the onreset and onsubmit attributes that can be set
-- on <form> elements.
-- ------------------------------
procedure Set_Form_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ON_RESET_ATTR'Access);
Names.Insert (ON_SUBMIT_ATTR'Access);
Names.Insert (ENCTYPE_ATTR'Access);
end Set_Form_Attributes;
--------------------
-- Add in the <b>names</b> set, the attributes which are specific to a link.
-- ------------------------------
procedure Set_Link_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (CHARSET_ATTR'Access);
Names.Insert (SHAPE_ATTR'Access);
Names.Insert (REV_ATTR'Access);
Names.Insert (COORDS_ATTR'Access);
Names.Insert (TARGET_ATTR'Access);
Names.Insert (HREFLANG_ATTR'Access);
end Set_Link_Attributes;
-- ------------------------------
-- Add in the <b>names</b> set, the attributes which are specific to an input file.
-- ------------------------------
procedure Set_File_Attributes (Names : in out Util.Strings.String_Set.Set) is
begin
Names.Insert (ACCEPT_ATTR'Access);
end Set_File_Attributes;
end ASF.Utils;
|
Add the onchange attribute on input elements
|
Add the onchange attribute on input elements
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
d5d56b3816599ff18ba7b19ec29a164940eb4246
|
src/gen-model-beans.ads
|
src/gen-model-beans.ads
|
-----------------------------------------------------------------------
-- gen-model-beans -- Ada Bean declarations
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Gen.Model.Tables;
package Gen.Model.Beans is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Bean Definition
-- ------------------------------
type Bean_Definition is new Tables.Table_Definition with null record;
type Bean_Definition_Access is access all Bean_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Bean_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Bean_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Bean_Definition);
-- Create an attribute with the given name and add it to the bean.
procedure Add_Attribute (Bean : in out Bean_Definition;
Name : in Unbounded_String;
Column : out Gen.Model.Tables.Column_Definition_Access);
-- Create a bean with the given name.
function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access;
end Gen.Model.Beans;
|
-----------------------------------------------------------------------
-- gen-model-beans -- Ada Bean declarations
-- 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 Gen.Model.Tables;
package Gen.Model.Beans is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Bean Definition
-- ------------------------------
type Bean_Definition is new Tables.Table_Definition with null record;
type Bean_Definition_Access is access all Bean_Definition'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Bean_Definition;
Name : in String) return Util.Beans.Objects.Object;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Bean_Definition);
-- Initialize the table definition instance.
overriding
procedure Initialize (O : in out Bean_Definition);
-- Create an attribute with the given name and add it to the bean.
procedure Add_Attribute (Bean : in out Bean_Definition;
Name : in Unbounded_String;
Column : out Gen.Model.Tables.Column_Definition_Access);
-- Create a bean with the given name.
function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access;
end Gen.Model.Beans;
|
Update copyright
|
Update copyright
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.